I was wondering, does memory_order_relaxed
allow unconstrained reordering of code on the same thread? For example:
// All on the same thread
std::atomic_int num(10);
std::cout << num.load(memory_order_relaxed) << "\n";
num.store(0, memory_order_relaxed);
Is it possible that 0 is printed? (In the actual code another thread is modifying num
, but its unrelated)
"Reordering" is not a useful way to think about multithreaded code, because it is so imprecise. Instead, we should observe the following:
a
and then atomic variable b
. Thread 2 may observe the new value of b
and then the old value of a
. This is what most people think of as "reordering".In your question, the answer is no, 0 cannot be printed. This is due to the first rule above: each thread executes in order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With