Thread Arguments

A thread gets its data by copy or by reference. Per default, you should use by copy. Why? In case your thread gets its data by reference, you have to be extremely careful about the lifetime of the arguments.

Precisely said, it is not the thread that gets the arguments in this example, but the lambda function. But that makes no difference for my argumentation. So the first thread t1 gets its data per copy ([=]), and the second thread t2 gets its data by reference ([&]).

What dangers are hidden in these lines? Thread t2 gets its string s by reference and is afterwards detached from the lifetime of its creator. On the one hand the lifetime of the string is bound to the lifetime of the invocation context, and on the other hand the lifetime of the global object std::cout is bound the lifetime of the main thread. So it may happen that the lifetime of the string s or the lifetime of std::cout is shorter than the lifetime of the thread t2. Now we are deep in the area of undefined behaviour.

Not convinced? Let's have a closer look, how undefined behaviour may look like.

The question is, which value does valSleeper have in line 26 valSleeper is a global variable. The thread t gets as work package a function object of type Sleeper together with the variable valSleeper and the number 5 (line 27). The crucial observation is, that the thread gets valSleeper by reference (line 9) and will be detached from the lifetime of the main thread (line 28). Then it will execute the call operator of the function object (line 10 - 16). In this method, it counts from 0 to 5, sleeps in each iteration 1/10 of a second and increments i by k. At the end, it displays its ID on the screen. Following Adam Riese (a German proverb), the result must be 1000 + 6 * 5 = 1030.

But, what happened? Something is going totally wrong.

There are two issues. On the one hand, valSleeper is 1000, on the other hand, the ID is missing on the console. So, that is undefined behaviour. The reason is that the lifetime of the main thread ends, before the child thread has performed its calculation or written its ID to std::cout.

In case, the main thread waits via t.join() until this child thread is done with its work, we get the expected result.

What's next?

Thinking about the lifetime of the threads is by far not the only issue with threads. Both threads, the main thread and the child thread share two objects. That is std::cout and the variable valSleeper. Now, I described the classical recipe for a data race or - to say it differently - for undefined behaviour. In the next post I will deal with shared variables between threads. (Proofreader Arne Mertz, Alexey Elymanov)

Go to Leanpub/cpplibrary"What every professional C++ programmer should know about the C++ standard library".Get your e-book. Support my blog.