Atomics Locks and Memory Ordering

⚓ Rust    📅 2026-02-23    👤 surdeus    👁️ 3      

surdeus

I have read total modification order means modification to same atomic variable twice in single thread using Relaxed memory ordering guarantees that modification happens in same order. It's only if different variables are modified then order is unpredictable. Am I right here?

static X: AtomicI32 = AtomicI32::new(0);

fn a() {
    X.fetch_add(5, Relaxed);
    X.fetch_add(10, Relaxed);
}

fn b() {
    let a = X.load(Relaxed);
    let b = X.load(Relaxed);
    println!("{a} {b}");
}

That means output can never be 10 15.

Also can anyone please explain me what can go wrong with below code if we use Relaxed ordering. I am confused as what operations compiler can reorder since all operations are dependent on previous operations.

fn get_data() -> &'static Data {
    static PTR: AtomicPtr<Data> = AtomicPtr::new(std::ptr::null_mut());

    let mut p = PTR.load(Acquire);

    if p.is_null() {
        p = Box::into_raw(Box::new(generate_data()));
        if let Err(e) = PTR.compare_exchange(
            std::ptr::null_mut(), p, Release, Acquire) {
                drop(unsafe{ Box::from_raw(p) });
                p = e;
        }
    }
    unsafe { &*p }
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed