Search code examples
c++c++11atomicstdatomic

When do I really need to use atomic<bool> instead of bool?


Isn't atomic<bool> redundant because bool is atomic by nature? I don't think it's possible to have a partially modified bool value. When do I really need to use atomic<bool> instead of bool?


Solution

  • No type in C++ is "atomic by nature" unless it is an std::atomic*-something. That's because the standard says so.

    In practice, the actual hardware instructions that are emitted to manipulate an std::atomic<bool> may (or may not) be the same as those for an ordinary bool, but being atomic is a larger concept with wider ramifications (e.g. restrictions on compiler re-ordering). Furthermore, some operations (like negation) are overloaded on the atomic operation to create a distinctly different instruction on the hardware than the native, non-atomic read-modify-write sequence of a non-atomic variable.