Can the assertion of the result of the atomic object fail?

Consider this example:

use std::sync::{atomic::{AtomicBool, AtomicI32, Ordering}, Arc};


fn main(){
	let flag = Arc::new(AtomicBool::new(false));
	let flag2 = flag.clone();
	let val = Arc::new(AtomicI32::new(0));
	let val2 = val.clone();
	let t1 = std::thread::spawn(move ||{
		val.store(1, Ordering::SeqCst);  // #1
		flag.store(true, Ordering::Relaxed);  // #2
	});
	let t2 = std::thread::spawn(move ||{
		while !flag2.load(Ordering::Relaxed){} // #3
		let r2 = val2.swap(3, Ordering::SeqCst);  // #4
		assert!(r2 == 1);  // #5
	});
	t1.join().unwrap();
	t2.join().unwrap();
}

Can the assertion at #5 fail?

1 Like

Yes. You are using flag to synchronize, not val, so its the ordering of flag that matters. The ordering of val is irrelevant.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.