What's wrong in this atomics example
⚓ Rust 📅 2026-03-24 👤 surdeus 👁️ 3use std::sync::atomic::Ordering::*;
use std::{
sync::atomic::{AtomicBool, AtomicUsize},
thread::spawn,
};
fn main() {
let x: &'static _ = Box::leak(Box::new(AtomicBool::new(false)));
let y: &'static _ = Box::leak(Box::new(AtomicBool::new(false)));
let z: &'static _ = Box::leak(Box::new(AtomicUsize::new(0)));
let _tx = spawn(|| {
x.store(true, Release);
});
let _ty = spawn(|| {
y.store(true, Release);
});
let t1 = spawn(move || {
while !x.load(Acquire) {}
if y.load(Acquire) {
z.fetch_add(1, Relaxed);
}
});
let t2 = spawn(move || {
while !y.load(Acquire) {}
if x.load(Acquire) {
z.fetch_add(1, Relaxed);
}
});
t1.join().unwrap();
t2.join().unwrap();
let _z = z.load(SeqCst);
}
in this example can someone please layout a possible execution for z holding a 0?
Also, is it possible for x.load to return false in t2 even when tx executed successfully and stored a true?
2 posts - 2 participants
🏷️ Rust_feed