Why can a reader see stale data behind a Relaxed flag?
Question
A producer writes 42 into PAYLOAD, then sets READY to true so a consumer can read PAYLOAD without a mutex. Both threads use Ordering::Relaxed.
- Why can the consumer still print
0after seeingREADY == true? - Why might tests pass on an x86-64 laptop yet fail on an ARM64 server?
- Fix the flag operations using the weakest memory ordering that guarantees
42.
static PAYLOAD: AtomicUsize = AtomicUsize::new(0);
static READY: AtomicBool = AtomicBool::new(false);
// Producer:
PAYLOAD.store(42, Ordering::Relaxed);
READY.store(true, Ordering::Relaxed);
// Consumer:
while !READY.load(Ordering::Relaxed) {}
println!("{}", PAYLOAD.load(Ordering::Relaxed));Show hints (3)
- "ATOMICITY WITHOUT ORDER"
Relaxedstops torn bytes on one variable, but puts zero ordering limits betweenPAYLOADandREADY. - "PAIR STORE AND LOAD"
The producer needs to seal prior accesses before publishing
READY. The consumer needs to stop later accesses from moving before checkingREADY. - "WEAKEST HAPPENS BEFORE"
Use
Ordering::Releaseon the store toREADYandOrdering::Acquireon the load fromREADY.
Show checked explanation
Ordering::Relaxed makes each individual access atomic, but lets the compiler or CPU reorder PAYLOAD and READY, so the consumer can see READY == true with stale PAYLOAD == 0. Store READY with Ordering::Release and load it with Ordering::Acquire to create a happens-before bridge. That is weaker than SeqCst and guarantees 42.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
static PAYLOAD: AtomicUsize = AtomicUsize::new(0);
static READY: AtomicBool = AtomicBool::new(false);
fn main() {
let writer = thread::spawn(|| {
PAYLOAD.store(42, Ordering::Relaxed);
READY.store(true, Ordering::Release);
});
while !READY.load(Ordering::Acquire) {
thread::yield_now();
}
println!("{}", PAYLOAD.load(Ordering::Relaxed));
writer.join().unwrap();
}42
Compiled and ran the Release-Acquire solution and a 10,000-round publish stress test with rustc 1.94.1 on Windows x64. Checked by an editor other than the author.
Walkthrough
Source line order is not what another CPU core automatically sees. Both the compiler optimizer and out-of-order CPU pipelines can reorder two Relaxed operations on different addresses. The producer can make READY = true visible before PAYLOAD = 42 drains from its store buffer, or the consumer can speculatively load PAYLOAD (0) before confirming READY is true.
Why x86-64 hides the bug. x86-64 has a strong hardware memory model (TSO) that preserves store-store and load-load order in hardware. Tests often pass by luck, though the compiler can still reorder Relaxed ops. ARM64 has a weakly ordered hardware model where cores freely observe writes out of program order unless release/acquire instructions are emitted.
| ordering | what it blocks | typical use |
|---|---|---|
Relaxed | Only torn reads/writes on one address | Standalone counters (fetch_add) |
Release / Acquire | No prior reads or writes move after Release; no later reads or writes move before Acquire | Publishing data behind a flag or lock |
SeqCst | All of the above plus one global order across all SeqCst ops | Multi-flag coordination (Dekker pattern) |
When the consumer's READY.load(Acquire) observes the true stored by READY.store(true, Release), the two operations synchronize-with each other. Everything sequenced before the Release store (including PAYLOAD.store(42, Relaxed)) happens-before everything sequenced after the Acquire load (including PAYLOAD.load(Relaxed)). Notice PAYLOAD itself can stay Relaxed because the Release/Acquire pair on READY already orders it.
Common mistakes
- Using
Releaseon the producer but leavingRelaxedon the consumer (or vice versa). Synchronization requires a matchingReleasestore paired with anAcquireload on the same atomic. - Thinking
Relaxedis fine on x86-64 forever. Even on x86-64, LLVM can reorderRelaxedoperations during optimization, and porting to ARM64 breaks it in hardware too. - Defaulting to
SeqCsteverywhere without knowing why, or dropping down toRelaxedwithout proving no other memory depends on the flag. - Spinning in
while !READY.load(Acquire) {}for long waits. Busy-spinning burns a full CPU core; useCondvar, a channel, orstd::thread::parkif the writer may take milliseconds.
Follow-up questions
- "If
PAYLOADwere a plain non-atomic struct insideUnsafeCell, wouldRelease/AcquireonREADYstill prevent a data race?" Yes, as long as the producer stops touchingPAYLOADbeforeREADY.store(true, Release)and the consumer only reads afterREADY.load(Acquire)returnstrue. Happens-before orders even non-atomic writes. - "When is
Release/Acquirenot enough, forcing you to useSeqCst?" When two threads write two different flags and each reads the other flag (store buffering, as in Dekker's algorithm).Release/Acquirestill allows both threads to readfalse;SeqCstenforces one global order. - "Does
Acquireflush the entire CPU cache?" No. Modern caches stay coherent automatically via protocols like MESI.ReleaseandAcquireconstrain compiler reordering and CPU store-buffer or load-reordering pipelines, not full cache flushes.
What a strong answer covers
Explains compiler and hardware reordering under Relaxed, contrasts x86-64 TSO with ARM64, pairs Release with Acquire on READY, and explains why PAYLOAD stays Relaxed.
Open in interactive practice deck →