Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) helgrind example 2: two counting threads using std::mutex

 

This helgrind example uses the same code as std::thread example 2: two counting threads using std::mutex.

 

 

 

 

 

 

Qt project file: CppHelgrindExample2.pro

 

#-------------------------------------------------
#
# Project created by QtCreator 2011-07-29T16:22:11
#
#-------------------------------------------------
QT       += core
QT       -= gui
QMAKE_CXXFLAGS += -std=c++0x
TARGET = CppHelgrindExample2
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <iostream>
#include <thread>

void DoCountDown(const int id)
{
  //static mutex, because each thread its must use the same mutex
  static std::mutex mutex;

  for (int i=0; i!=10; ++i)
  {
    ///Let this thread sleep, to give the other thread a chance
    std::this_thread::sleep_for(std::chrono::milliseconds(1));

    ///Acquire access to std::cout
    std::lock_guard<std::mutex> lock(mutex);

    ///Write to std::cout
    std::cout << "#" << id << ": " << (10-i) << '\n';
  }
}

int main()
{
  std::thread t1(DoCountDown,1);
  std::thread t2(DoCountDown,2);
  t1.join();
  t2.join();
}

 

 

 

 

 

helgrind.sh

 

#!/bin/sh
valgrind --tool=helgrind --log-file=helgrind.txt ../CppHelgrindExample2-build-desktop/./CppHelgrindExample2

 

 

 

 

 

Screen output

 

When starting the program using helgrind.sh, the following screen output is produced:

 

#1: 10
#2: 10
#1: 9
#2: 9
#1: 8
#2: 8
#1: 7
#2: 7
#1: 6
#2: 6
#1: 5
#2: 5
#1: 4
#2: 4
#1: 3
#2: 3
#1: 2
#2: 2
#1: 1
#2: 1

 

This is the same screen output when not using helgrind.

 

 

 

 

 

helgrind.txt

 

helgrind.txt is the output file created by helgrind:

 

==9780== Helgrind, a thread error detector
==9780== Copyright (C) 2007-2010, and GNU GPL'd, by OpenWorks LLP et al.
==9780== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==9780== Command: ../CppHelgrindExample2-build-desktop/./CppHelgrindExample2
==9780== Parent PID: 9779
==9780==
==9780==
==9780== For counts of detected and suppressed errors, rerun with: -v
==9780== Use --history-level=approx or =none to gain increased speed, at
==9780== the cost of reduced accuracy of conflicting-access information
==9780== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 145 from 14)

 

No errors!

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict