Here's a concrete example showing how relaxed ordering can produce unexpected results compared to acquire-release ordering:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> x{0};
std::atomic<int> y{0};
std::atomic<int> z{0};
void thread1() {
x.store(1, std::memory_order_relaxed);
y.store(1, std::memory_order_relaxed);
}
void thread2() {
while (y.load(std::memory_order_relaxed) == 0);
// At this point, y is 1, but x might still be 0!
z.store(x.load(std::memory_order_relaxed), std::memory_order_relaxed);
}
void thread3() {
while (z.load(std::memory_order_relaxed) == 0);
// z is non-zero, but it might be 0 (not 1)!
if (z.load(std::memory_order_relaxed) == 0) {
std::cout << "Unexpected: z is 0 even though we waited for it to be non-zero!\n";
}
}
With relaxed ordering, thread2 might see y=1 but x=0 because there's no synchronization between the stores in thread1. The store to x might not be visible yet when thread2 reads it, even though the store to y is visible. This can happen due to:
- Compiler reordering
- CPU store buffer delays
- Cache coherence timing
With acquire-release ordering:
void thread1_fixed() {
x.store(1, std::memory_order_relaxed);
y.store(1, std::memory_order_release); // Release barrier
}
void thread2_fixed() {
while (y.load(std::memory_order_acquire) == 0); // Acquire barrier
// Now x is guaranteed to be 1
z.store(x.load(std::memory_order_relaxed), std::memory_order_release);
}
void thread3_fixed() {
while (z.load(std::memory_order_acquire) == 0);
// z is guaranteed to be 1
}
The acquire-release synchronization creates a happens-before relationship: all memory operations before the release store in thread1 are visible to thread2 after its acquire load. This guarantees that when thread2 sees y=1, it will also see x=1, preventing the unexpected result where z could be 0.