Understanding Acquire and Release memory ordering

⚓ Rust    📅 2026-01-30    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

Can someone please explain how this differs from when we would have used Relaxed? Thank you!

#[test]
fn test() {
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering::{Release, Acquire};

    let x: &'static _ = Box::leak(Box::new(AtomicUsize::new(0)));
    let y: &'static _ = Box::leak(Box::new(AtomicUsize::new(0)));

    let h1 = std::thread::spawn(|| {
        let r1 = y.load(Acquire);
        x.store(r1, Release);
        r1
    });

    let h2 = std::thread::spawn(|| {
        let r2 = x.load(Acquire);
        y.store(42, Release);
        r2
    });

    let r1 = h1.join().unwrap();
    let r2 = h2.join().unwrap();

    println!("r1: {} r2: {}", r1, r2);
}

7 posts - 3 participants

Read full topic

🏷️ Rust_feed