Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a bool read/write operation be not atomic on x86? [duplicate]

Say we have two threads, one is reading a bool in a loop and another can toggle it at certain times. Personally I think this should be atomic because sizeof(bool) in C++ is 1 byte and you don't read/write bytes partially but I want to be 100% sure.

So yes or no?

EDIT:

Also for future reference, does the same apply to int?

like image 703
szx Avatar asked Jan 31 '13 11:01

szx


People also ask

Is bool Atomic on x86?

So yes, on x86 all std::atomic<> has to do for pure loads / pure stores is make sure values are naturally aligned, and not optimized away.

Does bool need to be atomic?

You need 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.


2 Answers

There are three separate issues that "atomic" types in C++11 address:

  1. tearing: a read or write involves multiple bus cycles, and a thread switch occurs in the middle of the operation; this can produce incorrect values.

  2. cache coherence: a write from one thread updates its processor's cache, but does not update global memory; a read from a different thread reads global memory, and doesn't see the updated value in the other processor's cache.

  3. compiler optimization: the compiler shuffles the order of reads and writes under the assumption that the values are not accessed from another thread, resulting in chaos.

Using std::atomic<bool> ensures that all three of these issues are managed correctly. Not using std::atomic<bool> leaves you guessing, with, at best, non-portable code.

like image 81
Pete Becker Avatar answered Oct 02 '22 21:10

Pete Becker


It all depends on what you actually mean by the word "atomic".

Do you mean "the final value will be updated in one go" (yes, on x86 that's definitely guaranteed for a byte value - and any correctly aligned value up to 64 bits at least), or "if I set this to true (or false), no other thread will read a different value after I've set it" (that's not quite such a certainty - you need a "lock" prefix to guarantee that).

like image 26
Mats Petersson Avatar answered Oct 02 '22 22:10

Mats Petersson