Program halts: atomics example run

⚓ Rust    📅 2026-03-15    👤 surdeus    👁️ 2      

surdeus

use std::sync::atomic::{
    AtomicBool, AtomicUsize,
    Ordering::{Acquire, Relaxed, Release},
};

static COUNTER: AtomicUsize = AtomicUsize::new(0);
static GIVER: AtomicUsize = AtomicUsize::new(10);
static BOOL: AtomicBool = AtomicBool::new(false);

fn main() {
    std::thread::scope(|s| {
        for _ in 0..10 {
            s.spawn(|| {
                let v = GIVER.load(Relaxed);
                let load = COUNTER.load(Relaxed);
                COUNTER.store(load + v, Relaxed);
                BOOL.store(true, Release);
            });
            s.spawn(|| {
                while BOOL
                    .compare_exchange_weak(true, false, Acquire, Relaxed)
                    .is_err()
                {}
                GIVER.fetch_sub(1, Relaxed);
            });
        }
    });
    let c = COUNTER.load(Relaxed);
    println!("{}", c);
}

I have used Acquire Release pair to establish a happens-before relationship such that the first thread (in a single iteration) should execute everything first and then the second thread will continue but, my program as the description says, halts...so what's wrong here?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed