Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 451
Benski Avatar asked Sep 20 '18 11:09

Benski


People also ask

What is an Atomic bool?

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.

Is bool Atomic C#?

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.

Is int atomic in C?

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.

Is assignment atomic in C++?

no, its not..... you need to use a locking primitive of some sort.


1 Answers

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.

like image 133
Geezer Avatar answered Sep 30 '22 01:09

Geezer