In a multi-threaded C++ app, do I need a mutex to protect a simple boolean?

Brian Stewart picture Brian Stewart · Oct 21, 2008 · Viewed 10.8k times · Source

I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronization, as the render loop needs to be pretty tight, and OSG itself tries to avoid having to ever lock. Most of the shared state is set before the thread is started, and never changed. I do have some data that does need to be changed, which I am planning to double-buffer. However, I have a simple boolean for signaling the thread to suspend rendering, and later resume rendering, and another to kill it. In both cases the app thread sets the bool, and the render thread only reads it. Do I need to synchronize access to these bools? As far as I can tell, the worse thing that could happen is the the render loop continues on for an extra frame before suspending or quitting.

Answer

Greg Hewgill picture Greg Hewgill · Oct 21, 2008

In C++11 and later, which has standards-defined concurrency, use std::atomic<bool> for this purpose. From http://en.cppreference.com/w/cpp/atomic/atomic:

If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).


The following old answer may have been true at some time in the past with some compilers and some operating environments, but it should not be relied upon today:

You're right, in this case you won't need to synchronise the bools. You should declare them volatile though, to ensure that the compiler actually reads them from memory each time, instead of caching the previous read in a thread (that's a simplified explanation, but it should do for this purpose).

The following question has more information about this: C++ Thread, shared data