How to test the behavior of std::memory_order_relaxed?

Or, is there any misunderstanding?

Yes there is one. What std::memory_order_relaxed allows in your program is for an implementation (a compiler) targeting an architecture, to produce a program which may observe the side effect r1 == r2 == 42.

An implementation does not have to produce such a program, and such a program does not have to produce that side effect; it is a possible outcome anyway.

How to test the behavior of std::memory_order_relaxed?

I cannot see a general solution to this question. You can only check that the side effect you observes matches with the specs of std::memory_order_relaxed.


Your code is a bit naive because by the time the 2nd thread starts the 1st one may have completed. The threads need to run these pieces of code truly concurrently.

For r1 == r2 == 42 to be true it requires load C to be reordered past store D, x86 does not do loads reordered after stores currently, so that you may never observe this kind of reordering on this platform (unless the compiler reorders C with D).

ARM and PowerPC, on the other hand, have weaker memory models. See Runtime memory ordering table.