Some colleagues and I are having a discussion about a relaxed atomic boolean that is used to synchronize two threads. We have done some online research and found other samples and snippets dealing with relaxed atomics but we fail to draw any conclusions from those that apply to our example.
The following atomic boolean is shared between two threads.
std::atomic_bool stopping{false};
The first thread enters a loop and only exits once the atomic boolean has been set. Note that the load on each loop iteration is marked relaxed.
// Thread 1
while (!stopping.load(std::memory_order_relaxed))
{
// ...
}
At some point after the first thread has entered the loop (guaranteed by some other synchronization mechanism), a second thread executes the following statement. Again, note that the store here is marked relaxed.
// Thread 2
stopping.store(true, std::memory_order_relaxed);
Question: from a purely theoretical point of view, is the first thread guaranteed to exit the loop; and why?
As far as we believe to understand relaxed atomics, we think the load operation is not guaranteed to see the modification of the write operation. But other online examples concerning thread-safe counters have made us believe the load is going to pick up the modification after all...
Thread 1 will go out of the loop after a finite period of time, this is a requirement of the language [basic.exec]/18:
N.B.: If thread 2, latter store
false
in the atomic, Thread 1 may never see the statetrue
of the atomic.N.B.2: I have just fall on the title of your question using relaxed atomic to synchronize thread: that is not possible.