Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) C++11 std::thread example 3: program flow

 

This thread example investigates the program flow from two simultaneously running threads.

 

The code I implemented after the talk given by Hans Boehm [1].

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppThreadExample3.pro

 

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

 

 

 

 

 

main.cpp

 

#include <algorithm>
#include <iostream>
#include <thread>

struct Tasks
{
  //static mutex, because each thread its must use the same mutex
  static std::mutex mutex;
  static int x;
  static int y;

  static void Task1()
  {
    x = 1;
    int r = y;

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

    ///Write to std::cout
    std::cout << "thread #1, x: " << x << ", copy of y: " << r << ", ";
  }
  static void Task2()
  {
    y = 1;
    int r = x;

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

    ///Write to std::cout
    std::cout << "thread #2, y: " << y << ", copy of x: " << r << ", ";
  }
};

std::mutex Tasks::mutex;
int Tasks::x = 0;
int Tasks::y = 0;

int main()
{
  std::thread t1(Tasks::Task1);
  std::thread t2(Tasks::Task2);
  t1.join();
  t2.join();
  std::cout << '\n';
}

 

 

 

 

 

CppThreadExample3.sh

 

#!/bin/bash
for ((i = 0;i<=1000;i++))
do
../CppThreadExample3-build-desktop/./CppThreadExample3 >> output.csv
done

 

 

 

 

 

Screen ouput

 

Screen output varies, so I used the script 'CppThreadExample3.sh' to let the program run a thousand times, so I could tally the output.

 

197x thread #1, x: 1, copy of y: 0, thread #2, y: 1, copy of x: 0,
 73x thread #1, x: 1, copy of y: 0, thread #2, y: 1, copy of x: 1,
242x thread #1, x: 1, copy of y: 1, thread #2, y: 1, copy of x: 0,
  0x thread #1, x: 1, copy of y: 1, thread #2, y: 1, copy of x: 1,
270x thread #2, y: 1, copy of x: 0, thread #1, x: 1, copy of y: 0,
217x thread #2, y: 1, copy of x: 0, thread #1, x: 1, copy of y: 1,
  2x thread #2, y: 1, copy of x: 1, thread #1, x: 1, copy of y: 0,
  0x thread #2, y: 1, copy of x: 1, thread #1, x: 1, copy of y: 1,

 

 

 

 

 

 

References

 

  1. Google TechTalk 'Getting C++ Threads Right' by Hans Boehm

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict