0

Does atomic operation synchronize between threads? I know that no one thread can see such operation undone, but does it synchronize? For example if I write to some var in one thread, and read after(in time domain) from another, is there possibility that I still can see old value?

  • `std::atomic` _"... If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see __memory model__ for details on data races)...."_ https://en.cppreference.com/w/cpp/atomic/atomic and https://en.cppreference.com/w/cpp/language/memory_model – Richard Critten Apr 19 '21 at 21:37
  • 1
    Are you talking about [cache coherence](https://en.wikipedia.org/wiki/Cache_coherence)? – tadman Apr 19 '21 at 21:38
  • 1
    Yes, it is definitely possible that a read, which takes place chronologically after a write from another thread, may return the old value, even when they are both atomic. (In fact the whole notion of "when" a read or write occurs is rather fuzzy.) The C++ Standard's memory model provides precise, though complicated, rules for what has to happen in order for you to be guaranteed to see the new value. – Nate Eldredge Apr 19 '21 at 21:53
  • Unless you explicitly enforce the order in the code, there is no guarantee that one thread will reach that point before any other threads. So you cannot assume the order of execution between threads. – stackoverblown Apr 19 '21 at 22:35

1 Answers1

1

Atomics by default provide sequential consistency (SC). SC doesn't need to respect the real time order. So it could be that after a write has executed (and even retired), when a different CPU does a load, it will not see that write. So in the real time order the load has occurred after the write, but in the memory order it has 'happened before' the write.

See the following answer for more info: Does 'volatile' guarantee that any thread reads the most recently written value?

pveentjer
  • 10,545
  • 3
  • 23
  • 40
  • Thanks for your answer! I've created another topic, could you please take a look at it? https://stackoverflow.com/questions/67173500/synchronization-of-stdatomiccompare-exchange-weak – questionmark Apr 20 '21 at 08:37