Possible Duplicate:
Concurrency: Atomic and volatile in C++11 memory model
With the C++11 <atomic> specification, is there any guarantee of freshness? The descriptions of different memory orders only deal with reorderings (as far as I’ve seen).
Specifically, in this situation:
#include <atomic>
std::atomic<int> cancel_work(0);
// Thread 1 is executing this function
void thread1_func() {
...
while (cancel_work.load(<some memory order>) == 0) {
...do work...
}
}
// Thread 2 executes this function
void thread2_func() {
...
cancel_work.store(1, <some memory order>);
...
}
If thread 1 and thread 2 do not share any other data except cancel_work, it seems to me that any ordering guarantees are not needed and std::memory_order_relax suffices for both the store and the load. But does this guarantee that thread 1 will ever see the update of cancel_work instead of just repeatedly reading its local cache line without ever refreshing it from main memory? If not, what is the minimum needed to make that guarantee?
There is nothing that will guarantee that: everything is about ordering. Even
memory_order_seq_cstjust guarantees that things happen in a single total order. In theory, the compiler/library/cpu could schedule every load fromcancel_storeat the end of the program.There is a general statement in 29.3p13 that
But there is no specification on what constitutes a “reasonable amount of time”.
So:
memory_order_relaxedshould be just fine, butmemory_order_seq_cstmay work better on some platforms, as the cache line may be reloaded sooner.