Search code examples
c++stdatomic

Synchronization problem with std::atomic<>


I have basically two questions that are closely related and they are both based on this SO question: Thread synchronization problem with c++ std::atomic variables

As cppreference.com explains:

For memory_order_acquire:

A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread

For memory_order_release: A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable

  1. Why people say that memory_order_seq_cst MUST be used in order for that example to work properly? What's the purpose of memory_order_acquire if it doesn't work as the official documentation says so? The documentation clearly says: All writes in other threads that release the same atomic variable are visible in the current thread.

  2. Why that example from SO question should never print "bad\n"? It just doesn't make any sense to me.

I did my homework by reading all available documentation, SO queastions/anwers, googling, etc... But, I'm still not able to understand some things.


Solution

  • Your linked question has two atomic variables, your "cppreference" quote specifically mentions "same atomic variable". That's why the reference text doesn't cover the linked question.

    Quoting further from cppreference: memory_order_seq_cst : "...a single total order exists in which all threads observe all modifications in the same order".

    So that does cover modifications to two atomic variables.

    Essentially, the design problem with memory_order_release is that it's a data equivalent of GOTO, which we know is a problem since Dijkstra. And memory_order_acquire is the equivalent of a COMEFROM, which is usually reserved for April Fools. I'm not yet convinced that they're good additions to C++.