Reputation: 1584
Consider the following code:
std::atomic<bool> flag(false);
//Thread 1
flag.store(true,std::memory_order_relaxed);
//Thread 2
while(!flag.load(std::memory_order_relaxed)) ; // stay in the loop
std::cout << "loaded";
Is there any gurantee that the last line ever gets executed? If the answer is no, how it should be fixed (with as minimum overhead as possible)?
Upvotes: 0
Views: 71
Reputation: 15941
Yes, the last line is guaranteed to be executed eventually [intro.progress]/18
An implementation should ensure that the last value (in modification order) assigned by an atomic or synchronization operation will become visible to all other threads in a finite period of time.
Since your flag is atomic and is also the only thing any thread ever accesses in any way, there are no data races here. Since there are no loads or stores to objects other than your atomic to begin with, your program cannot possibly depend on any particular ordering of such non-existent loads or stores relative to the loads and stores to your atomic. Thus, relaxed memory order is perfectly sufficient. Since it is guaranteed that the atomic store in thread 1 will eventually become visible to thread 2, the loop is guaranteed to eventually terminate…
Upvotes: 3