I have read the doc of std::memory_order_relaxed.
One part of explanation of Relaxed ordering is ....
// Thread 1: r1 = y.load(memory_order_relaxed); // A x.store(r1, memory_order_relaxed); // B // Thread 2: r2 = x.load(memory_order_relaxed); // C y.store(42, memory_order_relaxed); // D
and the explanation of this is said ...
[It] is allowed to produce
r1 == r2 == 42
. In particular, this may occur if D is completed before C in thread 2, either due to compiler reordering or at runtime.
I have understood the explanation, and try to test on my computer as following code:
std::atomic<int> x = {0};
std::atomic<int> y = {0};
int r1, r2;
void task1() {
// Thread 1:
r1 = y.load(memory_order_relaxed); // A
x.store(r1, memory_order_relaxed); // B
}
void task2() {
// Thread 2:
r2 = x.load(memory_order_relaxed); // C
y.store(42, memory_order_relaxed); // D
}
int main()
{
std::thread t2 (task2);
std::thread t1 (task1);
t1.join();
t2.join();
cout << "r1: " << r1
<< "\nr2: " << r2 << endl;
return 0;
}
The results of this code is never r1 == r2 == 42
, which is said that it's a possible behavior in that doc.
Is there any wrong in this code? Or, is there any misunderstanding?
r1==r2==42
on a classical computer. Maybe if you target an ARM CPU you could see it. – Oliv Sep 6 '18 at 11:03