Memory Ordering in Rust
All atomic operations take an ordering parameter that controls what guarantees we get about the relative ordering of operations.
[!NOTE] The CPU might decide to perform operations out of order, i.e., group all assignments together even if, in the code, they are not in that order. So T1 might see V1 V2 V3 getting assigned but T2 might see V2 V3 V1 in that order.
All atomic operations take in an Ordering parameter std::sync::atomic::Ordering, which controls what guarantees we get about the relative ordering of operations.
use std::thread;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
fn main() {
static STOP: AtomicBool = AtomicBool::new(false);
let bgt = thread::spawn(|| {
while !STOP.load(Relaxed) {
some_work();
}
});
for line in std::io::stdin().lines() {
match line.unwrap().as_str() {
"help" => println!("{}", help()),
"stop" => break,
cmd => println!("unknown command {cmd:?}"),
}
}
STOP.store(true, Relaxed);
bgt.join().unwrap();
}
The above code runs an infinite loop on a background thread till the user enters a stop command.
[!NOTE] If
some_work()is blocking and/or takes a while to finish, entering stop might not immediately stop the program; it will keep running until the last call tosome_workcompletes.
