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
?
6 Answers
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.
-
14small correction,
std::atomic_flag
is the only exception, although its name start with atomic also.– yngcccMay 1, 2013 at 15:25 -
8@yngccc: I think that's why Kerrek SB wrote
std::atomic*
and notstd::atomic<*>
. Oct 17, 2018 at 11:08 -
Remember about memory barriers. Although it may be impossible to change bool
partially, it is possible that multiprocessor system has this variable in multiple copies and one thread can see old value even after another thread has changed it to new. Atomic introduces memory barrier, so it becomes impossible.
-
4
-
11
-
18Just for clarity's sake. @Vincent's comment may have originated from an understanding of the keyword
volatile
in Java. Thevolatile
keyword in Java does control memory fences but has a very different behavior than thevolatile
keyword in C which does not. This question explains the difference further.– PaceDec 19, 2016 at 19:53 -
Why is atomicity tied to memory ordering? Does std::atomic<T> imply barriers? If so isn't that going a bit further than merely atomic?– nmrOct 18, 2017 at 20:05
-
5I think that's real correct answer. Because the answer about "standards bla-bla-bla... sizeof(bool) can be > 1 " is something that never happens in real life. All major compilers have sizeof(bool) == 1 and all read/write operations will work in a similar way for bool and atomic<bool>. But multi-core CPU and missed memory barrier is something that will happen with nearly 100% chance for any modern application and hardware– EzhSep 2, 2018 at 9:53
C++'s atomic types deal with three potential problems. First, a read or write can be torn by a task switch if the operation requires more than one bus operation (and that can happen to a bool
, depending on how it's implemented). Second, a read or write may affect only the cache associated with the processor that's doing the operation, and other processors may have a different value in their cache. Third, the compiler can rearrange the order of operations if they don't affect the result (the constraints are a bit more complicated, but that's sufficient for now).
You can deal with each of these three problems on your own by making assumptions about how the types you are using are implemented, by explicitly flushing caches, and by using compiler-specific options to prevent reordering (and, no, volatile
doesn't do this unless your compiler documentation says it does).
But why go through all that? atomic
takes care of it for you, and probably does a better job than you can do on your own.
-
Task switches don't cause tearing unless it took multiple instructions to store the variable. Whole instructions are atomic wrt. interrupts on a single core (they either fully complete before the interrupt, or any partial work is discarded. This is part of what store buffers are for.) Tearing is far more likely between threads on separate cores that are actually running simultaneously, because then yes you can get tearing between the parts of a store done by one instruction, e.g. an unaligned store or one too wide for the bus. Jul 3, 2019 at 20:27
-
No, a core can't write a cache line until it has exclusive ownership of that line. The MESI cache coherency protocol ensures this. (See Can num++ be atomic for 'int num'?). The real problem for C++ is that the compiler is allowed to assume that non-atomic variables aren't changed by other threads, so it can hoist loads out of loops and keep them in registers or optimize away. e.g. turning
while(!var) {}
intoif(!var) infloop();
. This part ofatomic
is similar to whatvolatile
does: always re-read from memory (which is cached but coherent). Jul 3, 2019 at 20:30 -
1@PeterCordes — I don’t have the wisdom to make assertions about the behavior of every possible hardware architecture that C++ code could be run on. Maybe you do, but that doesn’t mean you should resurrect a six-year old thread. Jul 3, 2019 at 20:32
-
1An efficient C++ implementation on a machine that required explicit coherency sounds unlikely, so it's a weird one to make up when keeping values in registers produces the same problem you're talking about via a mechanism that does exist on all real CPUs. What bugs me about this answer is that it's not helping to clear up the common misconception about cache coherency in the real systems we do use. Many people think that explicit flushing of some kind is necessary on x86 or ARM, and that reading stale data from cache is possible. Jul 5, 2019 at 0:56
-
1If the C++ standard cared at all about efficiency on non-coherent shared memory running multiple threads, there'd be mechanisms like release-stores that only made a certain array or other object globally visible, not every other operation before that point (including all non-atomic ops). On coherent systems, release stores just have to wait for preceding in-flight loads/stores to complete and commit, not write back the whole contents of any private caches. Access to our dirty private caches by other cores happens on demand. Jul 5, 2019 at 1:00
Consider a compare and exchange operation:
bool a = ...;
bool b = ...;
if (a)
swap(a,b);
After we read a, we get true, another thread could come along and set a false, we then swap (a,b), so after exit b is false, even though the swap was made.
Using std::atomic::compare_exchange
we can do the entire if/swap logic atomically such that the other thread could not set a to false in between the if and the swap (without locking). In such a circumstance if the swap was made than b must be false on exit.
This is just one example of an atomic operation that applies to a two value type such as bool.
-
2How come this is the lowest rated answer? This (or test_and_set in std::atomic_flag) is the main reason to use an atomic bool type.– SzocskeDec 2, 2015 at 18:55
Atomic operations are about more than just torn values, so while I agree with you and other posters that I am not aware of an environment where torn bool
is a possibility, there is more at stake.
Herb Sutter gave a great talk about this which you can view online. Be warned, it is a long and involved talk. Herb Sutter, Atomic Weapons. The issue boils down to avoiding data races because it allows you to have the illusion of sequential consistency.
Atomicity of certain types depends exclusively on the underlying hardware. Each processor architecture has different guarantees about atomicity of certain operations. For example:
The Intel486 processor (and newer processors since) guarantees that the following basic memory operations will always be carried out atomically:
- Reading or writing a byte
- Reading or writing a word aligned on a 16-bit boundary
- Reading or writing a doubleword aligned on a 32-bit boundary
Other architectures have different specifications on which operations are atomic.
C++ is a high-level programming language that strives to abstract you from the underlying hardware. For this reason standard simply cannot permit one to rely on such low-level assumptions because otherwise your application wouldn't be portable. Accordingly, all the primitive types in C++ are provided with atomic
counterparts by C++11 compliant standard library out-of-the-box.
-
3Another critical part is that C++ compilers are normally allowed to keep variables in registers or optimize away accesses, because they can assume that no other threads are changing the value. (Because of data-race UB).
atomic
sort of includes this property ofvolatile
, sowhile(!var){}
can't optimize intoif(!var) infinite_loop();
. See MCU programming - C++ O2 optimization breaks while loop Jul 3, 2019 at 20:46
atomic<bool>
to avoid race-conditions. A race-condition occurs if two threads access the same memory location, and at least one of them is a write operation. If your program contains race-conditions, the behavior is undefined.int
value where you are copying each byte or word of that value individually. There therefore shouldn't be any race condition, if the write is already atomic.