Someone who commented on the accepted answer claims that one cannot use a simple bool variable as a signal, the code was broken without a memory barrier and using std::atomic would be correct.
The commenter is right: a simple bool
is insufficient, because non-atomic writes from the thread that sets thread_finished
to true
can be re-ordered.
Consider a thread that sets a static variable x
to some very important number, and then signals its exit, like this:
x = 42;
thread_finished = true;
When your main thread sees thread_finished
set to true
, it assumes that the worker thread has finished. However, when your main thread examines x
, it may find it set to a wrong number, because the two writes above have been re-ordered.
Of course this is only a simplified example to illustrate the general problem. Using std::atomic
for your thread_finished
variable adds a memory barrier, making sure that all writes before it are done. This fixes the potential problem of out-of-order writes.
Another issue is that reads to non-volatile variables can be optimized out, so the main thread would never notice the change in the thread_finished
flag.
Important note: making your
thread_finished
volatile is not going to fix the problem; in fact, volatile should not be used in conjunction with threading - it is intended for working with memory-mapped hardware.