Search code examples
c++concurrencyatomic

C++: Is the assignment of a value to a primitive data type (e.g. bool) an atomic operation?


Imagine having two threads, one assigning a value to a (already initialised) bool and another thread reading/checking this bool. Thread sanitizers might detect a possible data race here if the accesses to the bool are not guarded or the bool is non-atomic.

How is this possible? Is it possible that assigning to a bool is not always atomic, e.g., because of hardware characteristics like cache hierarchies or out-of-order execution?


Solution

  • Even though the C++ standard does not mandate so, it is not possible in practice to get a tearing effect "in the middle" of a bool on x86, i.e. change the value only partially while another thread is accessing it. It is, however, possible that a CPU is maintaining more than one copy of it, as a cache for each core for example. Hence, one thread could be "seeing" an older value after another thread finished changing it to a new one. std::atomic (and specifically in your case std::atomic<bool>) provides you with memory barriers to remedy this issue.