C++11 multithreading tutorial - part 3
Posted on May 9, 2012 by Paul
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:
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:
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:
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: