c++optimizationllvmvolatile

Everything is volatile


I'm creating this multithreaded C++ program and upon compiling in Release mode, I'm finding bugs of the sort (object still null) ie, it looks like missing volatile markers.

But the problem is, since there is a 2nd worker thread touching all kinds of objects, it means that virtually everything is volatile in the program.

I'm wondering if there is a way to turn off optimizations in the Apple LLVM compiler that create the bugs the volatile keyword was specifically designed to fix. These bugs don't show up in debug mode (because optimizations are off). Putting volatile everywhere basically means peppering every class with volatile after every member function, and adding volatile before every shared variable declaration.

I think I'd rather lose that volatile optimization than risk a spurious bug showing up because I forgot to mark something volatile.


Solution

  • In C++, volatile has nothing to do with thread safety. You cannot rely on it to avoid data races. Its purpose is to force synchronised accesses to a variable (from a single thread, or threads that use some other mechanism to synchronise with each other) to happen exactly in the order specified. This is often necessary when interacting with hardware, to prevent accesses that appear to do nothing, but actually affect the state of the hardware, from being optimised away. It gives no guarantees about the effect of unsynchronised accesses.

    To avoid data races, you must use either atomic operations or explicit locks to synchronise access to shared objects. C++11 provides these in the standard library; if you're stuck in the past, then you'll have to rely on whatever libraries (such as pthreads) or language extensions (such as atomic intrinsics) are available on your platform.