Can a bool read/write operation be not atomic on x86?

szx picture szx · Jan 31, 2013 · Viewed 13.4k times · Source

Say we have two threads, one is reading a bool in a loop and another can toggle it at certain times. Personally I think this should be atomic because sizeof(bool) in C++ is 1 byte and you don't read/write bytes partially but I want to be 100% sure.

So yes or no?

EDIT:

Also for future reference, does the same apply to int?

Answer

Pete Becker picture Pete Becker · Jan 31, 2013

There are three separate issues that "atomic" types in C++11 address:

  1. tearing: a read or write involves multiple bus cycles, and a thread switch occurs in the middle of the operation; this can produce incorrect values.

  2. cache coherence: a write from one thread updates its processor's cache, but does not update global memory; a read from a different thread reads global memory, and doesn't see the updated value in the other processor's cache.

  3. compiler optimization: the compiler shuffles the order of reads and writes under the assumption that the values are not accessed from another thread, resulting in chaos.

Using std::atomic<bool> ensures that all three of these issues are managed correctly. Not using std::atomic<bool> leaves you guessing, with, at best, non-portable code.