Consider the below code:
static std::atomic<int> x;
// Thread 1
x.store(7, std::memory_order_relaxed);
// Thread 2
x.load(std::memory_order_relaxed);
Further assume that Thread 2 executed the load
a few cycles after Thread 1 executed the store
.
Is it guaranteed that Thread 2 would read the value 7
on all hardware platforms? In other words, after Thread 1 executed the store
, is it guaranteed that the value 7 would be immediately visible to threads the do a relaxed load of the same variable later?
Yes, it will be visible. It has become somewhat a common question regarding relaxed memory orders and what they do in contrast to stronger memory orders.
A memory order stronger then memory order relaxed does the following two things:
Different orders guarantee different synchronization strategies (only reads, only writes, reads and writes) and different reordering preventations (only what is executed before the instruction, only what is executed after the instruction or both). Memory order relaxed doesn't guarantee any of those, it only guarantees that atomic variables are visible across threads.
In your example there is no other instruction other than the store in one thread, and a load in another. Plus, there is no non-atomic memory to synchronize across threads, the only memory is already atomic.
So there is no need to use something heavier than memory_order_relaxed
. The snippet above is valid and will produce the wanted result.