Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can relaxed memory model reorder on same thread?

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)

like image 403
ABCQWEPOI Avatar asked Oct 15 '25 22:10

ABCQWEPOI


1 Answers

"Reordering" is not a useful way to think about multithreaded code, because it is so imprecise. Instead, we should observe the following:

  • Each thread executes in order.
  • Each atomic variable in the program has a single modification order, on which all threads agree.
  • There is no single order in which different atomic variables are modified (unless such atomic variables are accessed solely through sequentially consistent operations).
  • A thread might not observe side effects on two different atomic variables modified by another thread in the same order in which such modifications actually occurred. For example, thread 1 can modify atomic variable 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.

like image 108
Brian Bi Avatar answered Oct 17 '25 13:10

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!