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?
AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables.
Yes. Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. as found in C# Language Spec.
In practice, you can assume that int is atomic. You can also assume that pointer types are atomic; that is very convenient. Both of these assumptions are true on all of the machines that the GNU C Library supports and on all POSIX systems we know of.
no, its not..... you need to use a locking primitive of some sort.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With