Fences Order Flag And Payload

A Release fence before publishing a flag pairs with an Acquire fence after observing it, so payload writes are visible without atomic ordering on each access.

RustResilience

Code

rustsnippet
25 lines
use std::hint::spin_loop;
use std::sync::atomic::{fence, AtomicBool, AtomicU32, Ordering};
use std::thread;

static READY: AtomicBool = AtomicBool::new(false);
static PAYLOAD: AtomicU32 = AtomicU32::new(0);

fn main() {
    let worker = thread::spawn(|| {
        PAYLOAD.store(2026, Ordering::Relaxed);
        // fence(Release):PAYLOAD 的写入不得重排到 READY 置真之后
        fence(Ordering::Release);
        READY.store(true, Ordering::Relaxed);
    });

    // 演示用自旋等待;生产环境更常挂起等待(condvar/通道)
    while !READY.load(Ordering::Relaxed) {
        spin_loop();
    }
    // 配对 fence(Acquire):之后的读取一定能看到 2026
    fence(Ordering::Acquire);
    println!("payload: {}", PAYLOAD.load(Ordering::Relaxed));

    worker.join().unwrap();
}

How the logic is organized

The snippet is organized around the function main.

The file repeats itself only inside while !READY.load(Ordering::Relaxed).

What to watch for

  • The whole dependency story is the language version itself.

Using it

Entry signature: fn main()

Labels appear in the output — payload: — when the file runs.

Key statements

worker.join().unwrap();

Interactive Tools for This Topic

FAQ

What does Fences Order Flag And Payload print when run?
Invoke the file as-is — the `payload:` prefixes identify which step printed each line.