C++11 multithreading tutorial - part 3
Posted on May 9, 2012 by Sol

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 e.g.) 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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <thread>
#include <string>

using namespace std;

class SaylHello{
public:

  //This function will be called from a thread
  void func(const string &name) {
     cout <<"Hello " << name << endl;
  };
};

int main(int argc, char* argv[])
{
  SaylHello x;

  //Use a member function in a thread
  thread t(&SaylHello::func, &x, "Tom");

  //Join the thread with the main thread
  t.join();

  return 0;
}

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
  //Use of an anonymous function (lambda) in a thread
  thread t( [] (string name) {
    cout << "Hello " << name << endl;
  }, "Tom");

  //Join the thread with the main thread
  t.join();

  return 0;
}

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
sols-MacBook-Pro:thread3 sol$ clear
sols-MacBook-Pro:thread3 sol$ g++-4.7 -std=c++11 threads_00.cpp
sols-MacBook-Pro:thread3 sol$ ./a.out
Hello Tom
sols-MacBook-Pro:thread3 sol$ g++-4.7 -std=c++11 threads_01.cpp
sols-MacBook-Pro:thread3 sol$ ./a.out
Hello Tom
sols-MacBook-Pro:thread3 sol$ clang++ -std=c++11 -stdlib=libc++ threads_00.cpp
sols-MacBook-Pro:thread3 sol$ ./a.out
Hello Tom
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: Practical Multithreading by Anthony Williams:

blog comments powered by Disqus