Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) C++11 std::thread example 1: two counting threads

 

This std::thread examples shows the code and screen output of two threads counting down. Below it, the code is discussed in more detail.

 

 

#include <iostream>
#include <thread>

void DoCountDown(const int id)
{
  for (int i=0; i!=10; ++i)
  {
    std::cout << "#" << id << ": " << (10-i) << '\n';
  }
}

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

 

Screen output:

 

##12: : 10
10#
#1: 29
: #9
#12: : 8
#8
2: #7
#12: : 7
#61
: #6
#21: : 5
5#1
: #4
#2: 14
: #3
#21: : 2
3#
1#: 2: 21

#2: 1

 

Note the following about the code:

 

This example is checked for errors in helgrind example 1: two counting threads, where helgrind is shown to detect race conditions.

 

The next example, std::thread example 2: two counting threads using std::mutex demonstrates how to use std::mutexes to share std::cout nicely.

 

 

 

 

 

References

 

  1. Bjarne Stroustrup's C++0x page

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict