compare_exchange CAS Retry For Atomic Claims

compare_exchange_weak claims stock atomically and retries on contention, so concurrent buyers decrement exactly once each and never oversell.

RustResilience

Code

rustsnippet
34 lines
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;

fn main() {
    let stock = Arc::new(AtomicU32::new(5));
    let buyers: Vec<_> = (0..8)
        .map(|_| {
            let stock = Arc::clone(&stock);
            thread::spawn(move || {
                loop {
                    let current = stock.load(Ordering::Relaxed);
                    if current == 0 {
                        return false; // 售罄
                    }
                    // CAS claims: decrement only if the value is unchanged; retry on contention
                    match stock.compare_exchange_weak(
                        current,
                        current - 1,
                        Ordering::SeqCst,
                        Ordering::Relaxed,
                    ) {
                        Ok(_) => return true,
                        Err(_) => continue,
                    }
                }
            })
        })
        .collect();

    let results: Vec<bool> = buyers.into_iter().map(|h| h.join().unwrap()).collect();
    let claimed = results.iter().filter(|r| **r).count();
    println!("claimed {claimed}, left {}", stock.load(Ordering::SeqCst));
}

How it works

Every runnable line is contained in the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Watch out for

  • No packages pulled in; the language’s built-in APIs carry all of the work here.

Using it

Signature: fn main()

The demo output is labeled (claimed), so each printed line points back to the operation that produced it.

Key statements worth quoting

let results: Vec<bool> = buyers.into_iter().map(|h| h.join().unwrap()).collect();
let claimed = results.iter().filter(|r| **r).count();
return false; // 售罄
}

Interactive Tools for This Topic

FAQ

What does compare_exchange CAS Retry For Atomic Claims print when run?
No setup needed: run the file and look for labeled lines like `claimed` in the output.