Someone who commented on the accepted answer claims that you 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 comment is correct: a simple bool not enough, because non-atomic entries from a thread that sets from thread_finished to true can be reordered.
Consider a thread that sets the static variable x to some very important number, and then signals its output, for example:
x = 42; thread_finished = true;
When your main thread sees thread_finished set to true , it assumes the worker thread has completed. However, when your main thread checks for x , it can determine that it is set to the wrong number because the two entries above were reordered.
Of course, this is just a simplified example illustrating a common problem. Using std::atomic for your thread_finished variable adds a memory barrier, ensuring that all writes are completed before it is complete. This fixes a potential out-of-band recording problem.
Another problem is that reading non-volatile variables can be optimized therefore, the main thread will never notice a change in the thread_finished icon.
Important notice: make your
thread_finished volatile
not to fix the problem; in fact, volatile should not be used in conjunction with stream processing - it is designed to work with hardware mapped to memory.
dasblinkenlight Jan 16 '13 at 19:04 on 2013-01-16 19:04
source share