I'd like to know the following:
for example:
std::atomic<uint8_t> i=0;
thr1_func()
{
i.store(1,std::memory_order_relaxed);//here is first step
}
thr2_func()
{
while(!i.load(std::memory_order_relaxed);//here is next step
}
Will 'i' variable have new value on first load operation after store operation ? Or may 'i' variable have new value on second or other execution of the command?
thank u in advance.
Does second thread see the new value on the next load operation?
If the next load
operation happens after store
in modification order of that atomic variable then that load
read the value from that store
.
See std::memory_order
for full details:
Modification order
All modifications to any particular atomic variable occur in a total order that is specific to this one atomic variable.
...
- Write-read coherence: if a side effect (a write) X on an atomic object M happens-before a value computation (a read) B of M, then the evaluation B shall take its value from X or from a side effect Y that follows X in the modification order of M
Also, in [atomics.order]
the standard says that:
Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.
In practice that means that the compiler issues those store and load instructions and then it is up to the hardware to propagate the stored value and make it visible to other CPUs. x86 CPUs use a store buffer, so that the stored new value goes into the store buffer first and becomes visible to other CPUs some (small) time after it left the store buffer. During that time the CPU that stored the value can read it back from the store buffer, but other CPUs cannot.
Some more information: How do I make memory stores in one thread "promptly" visible in other threads?