C++11 multithreading tutorial - part 3

The code for this tutorial is on GitHub: https://github.com/sol-prog/threads.

In my previous two tutorials about C++11 threads:

we’ve seen that C++11 allows us to use a clean syntax (compared with the one used by POSIX) for managing multithread applications. The second tutorial presents an example of threads synchronization using mutex and atomic operations. In this tutorial I’m going to show you how to use a member function and lambda with threads.

We’ll start with a simple example of a C++11 thread with a member function:

1 #include <iostream> 2 #include <thread> 3 #include <string> 4 5 using namespace std ; 6 7 class SaylHello { 8 public : 9 10 //This function will be called from a thread 11 void func ( const string & name ) { 12 cout << "Hello " << name << endl ; 13 }; 14 }; 15 16 int main ( int argc , char * argv []) 17 { 18 SaylHello x ; 19 20 //Use a member function in a thread 21 thread t ( & SaylHello :: func , & x , "Tom" ); 22 23 //Join the thread with the main thread 24 t . join (); 25 26 return 0 ; 27 }

In the above example we use a dummy class with a public function that can be called from a thread, at line 21 in the source file you can see the way in which you can pass an argument to this function.

C++11 also allows us to use anonymous functions, or lambdas, in a thread:

1 #include <iostream> 2 #include <thread> 3 #include <string> 4 5 using namespace std ; 6 7 int main ( int argc , char * argv []) 8 { 9 //Use of an anonymous function (lambda) in a thread 10 thread t ( [] ( string name ) { 11 cout << "Hello " << name << endl ; 12 }, "Tom" ); 13 14 //Join the thread with the main thread 15 t . join (); 16 17 return 0 ; 18 }

The above codes can be compiled with gcc-4.7 on Linux and Mac or with Visual Studio 11 on Windows. You can also use Clang for Mac and Linux for compiling the first example, currently Clang can’t compile anonymous functions:

1 sols-MacBook-Pro:thread3 sol$ clear 2 sols-MacBook-Pro:thread3 sol$ g++-4.7 -std = c++11 threads_00.cpp 3 sols-MacBook-Pro:thread3 sol$ ./a.out 4 Hello Tom 5 sols-MacBook-Pro:thread3 sol$ g++-4.7 -std = c++11 threads_01.cpp 6 sols-MacBook-Pro:thread3 sol$ ./a.out 7 Hello Tom 8 sols-MacBook-Pro:thread3 sol$ clang++ -std = c++11 -stdlib = libc++ threads_00.cpp 9 sols-MacBook-Pro:thread3 sol$ ./a.out 10 Hello Tom 11 sols-MacBook-Pro:thread3 sol$

If you are interested in learning more about the new C++11 syntax I would recommend reading Professional C++ by M. Gregoire, N. A. Solter, S. J. Kleper 2nd edition:

or, if you are a C++ beginner you could read C++ Primer (5th Edition) by S. B. Lippman, J. Lajoie, B. E. Moo.

A good book for learning about C++11 multithreading support is C++ Concurrency in Action by Anthony Williams: