27

I'm just reading the C++ concurrency in action book by Anthony Williams. There is this classic example with two threads, one produce data, the other one consumes the data and A.W. wrote that code pretty clear :

std::vector<int> data;
std::atomic<bool> data_ready(false);

void reader_thread()
{
    while(!data_ready.load())
    {
        std::this_thread::sleep(std::milliseconds(1));
    }
    std::cout << "The answer=" << data[0] << "\n";
}

void writer_thread()
{
    data.push_back(42);
    data_ready = true;
}

And I really don't understand why this code differs from one where I'd use a classic volatile bool instead of the atomic one. If someone could open my mind on the subject, I'd be grateful. Thanks.

4
  • 7
    With a regular bool, the optimizer might rearrange your code to only check the value of data_ready once since (naively) its value cannot change once the while is entered, producing an infinite loop.
    – dlf
    Commented Apr 14, 2015 at 17:03
  • 3
    @dlf: Only if it can prove that sleep won't affect the value.
    – Ben Voigt
    Commented Apr 14, 2015 at 17:12
  • @dlf I'm Ok with that, i should added volatile bool as Max Truxa said to be sure that the data is load from memory and not cache memory
    – takezo
    Commented Apr 14, 2015 at 17:24
  • If you load and store the atomic<bool> with memory_order_relaxed, there's no difference to a volatile bool. So in this case it's just a matter of taste. Commented Dec 31, 2019 at 5:30

3 Answers 3

21

A "classic" bool, as you put it, would not work reliably (if at all). One reason for this is that the compiler could (and most likely does, at least with optimizations enabled) load data_ready only once from memory, because there is no indication that it ever changes in the context of reader_thread.

You could work around this problem by using volatile bool to enforce loading it every time (which would probably seem to work) but this would still be undefined behavior regarding the C++ standard because the access to the variable is neither synchronized nor atomic.

You could enforce synchronization using the locking facilities from the mutex header, but this would introduce (in your example) unnecessary overhead (hence std::atomic).


The problem with volatile is that it only guarantees that instructions are not omitted and the instruction ordering is preserved. volatile does not guarantee a memory barrier to enforce cache coherence. What this means is that writer_thread on processor A can write the value to it's cache (and maybe even to the main memory) without reader_thread on processor B seeing it, because the cache of processor B is not consistent with the cache of processor A. For a more thorough explanation see memory barrier and cache coherence on Wikipedia.


There can be additional problems with more complex expressions than x = y (i.e. x += y) that would require synchronization through a lock (or in this simple case an atomic +=) to ensure the value of x does not change during processing.

x += y for example is actually:

  • read x
  • compute x + y
  • write result back to x

If a context switch to another thread occurs during the computation this can result in something like this (2 threads, both doing x += 2; assuming x = 0):

Thread A                 Thread B
------------------------ ------------------------
read x (0)
compute x (0) + 2
                 <context switch>
                         read x (0)
                         compute x (0) + 2
                         write x (2)
                 <context switch>
write x (2)

Now x = 2 even though there were two += 2 computations. This effect is known as tearing.

5
  • Ok thanks, i've ust edited the topic cause you'right, i should have precise a bool with the volatile type modifier. Still i don't understand when you say that the access to the variable is neither synchronized nor atomic
    – takezo
    Commented Apr 14, 2015 at 17:29
  • I updated my answer. See the section below the first ruler. The last part is just me being thorough and maybe preventing followup questions ;)
    – Max Truxa
    Commented Apr 14, 2015 at 18:03
  • Ok, i understood that the atomic bool force the storage in memory so that the reader thread can read the updated value correctly immediately. Unlike the volatile bool where the write can be done in registers and put in memory later so that there is latency and the reader thread read the old value whereas the update has been done but "in registers" only. I really thank you all of you :)
    – takezo
    Commented Apr 14, 2015 at 19:13
  • The exact behavior is architecture-dependent and you can't/shouldn't make any assumptions about this. E.g. on a multiprocessor system, even if the register containing the value is written to the processor's cache the changes may not be visible to the other processors on the system until the cache line containing the variable is written back to the main memory and even then, the other processors will only see the value after they reload the memory area in question. This topic becomes quite complex if you start looking at techniques like snooping.
    – Max Truxa
    Commented Apr 14, 2015 at 19:35
  • The whole point about declaring architecture-specific things like this as undefined behavior in the standard is to enable programmers to write code that is portable and doesn't rely on things that break on the second system it is executed on.
    – Max Truxa
    Commented Apr 14, 2015 at 20:19
16

The big difference is that this code is correct, while the version with bool instead of atomic<bool> has undefined behavior.

These two lines of code create a race condition (formally, a conflict) because they read from and write to the same variable:

Reader

while (!data_ready)

And writer

data_ready = true;

And a race condition on a normal variable causes undefined behavior, according to the C++11 memory model.

The rules are found in section 1.10 of the Standard, the most relevant being:

Two actions are potentially concurrent if

  • they are performed by different threads, or
  • they are unsequenced, and at least one is performed by a signal handler.

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

You can see that whether the variable is atomic<bool> makes a very big difference to this rule.

9
  • 2
    Ok, there is a race condition, but eventually, the consequence are juste another round of while loop if the bool is read before the store. For the undefined behavior since bool can only have two states, true or false. So when a bool variable is set to false, one juste have to modifiy one bit to make it true. So how can undefined behavior can happen here. Undefined behavior happens when there is a race condition and one thread can see an object in a half state which is inconsistent. So from my point of view, bool or std::atomic<bool> is the same in terms of code results.
    – takezo
    Commented Apr 14, 2015 at 17:20
  • 4
    @jedib: Undefined behaviour happens because the behaviour is undefined. If your asking for specific examples of erroneous behaviour that might arise in this particular case: without a memory barrier, the reading thread might see the bool change before its view of the vector is updated. Or it might not see the change at all, on a processor that doesn't guarantee cache coherency. Commented Apr 14, 2015 at 17:23
  • 1
    @Mike: Or, the optimizer might remove the while loop completely, on the grounds that data_ready cannot be and remain false forever (since that violates the making-progress rule) and cannot be false and later change from false to true (since that can only happen due to a conflicting write) and therefore the only remaining possibility is that data_ready is already true, the while loop is never entered, and is removed as dead code.
    – Ben Voigt
    Commented Apr 14, 2015 at 17:52
  • @jedib: Your error is in attempted to redefine "undefined behavior" to mean "any behavior that jedib can imagine". The reality is much worse. Code that exhibits undefined behavior is optimization unstable
    – Ben Voigt
    Commented Apr 14, 2015 at 17:58
  • 1
    @BenVoigt What? How can the optimizer remove the while loop completely? Is there a real life example of your statement? The whole idea behind "volatile" is to tell optimizer to don't interfere!
    – AA.
    Commented Dec 28, 2020 at 14:01
7

Ben Voigt's answer is completely correct, still a little theoretical, and as I've been asked by a colleague "what does this mean for me", I decided to try my luck with a little more practical answer.

With your sample, the "simplest" optimization problem that could occur is the following:

According to the Standard, an optimized execution order may not change the functionality of a program. Problem is, this is only true for single threaded programs, or single threads in multithreaded programs.

So, for writer_thread and a (volatile) bool

data.push_back(42);
data_ready = true;

and

data_ready = true;
data.push_back(42);

are equivalent.

The result is, that

std::cout << "The answer=" << data[0] << "\n";

can be executed without having pushed any value into data.

An atomic bool does prevent this kind of optimization, as per definition it may not be reordered. There are flags for atomic operations which allow statements to be moved in front of the operation but not to the back, and vice versa, but those require a really advanced knowledge of your programming structure and the problems it can cause...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.