Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 14, 2025 08:52
Show Gist options
  • Select an option

  • Save rust-play/544ee0cef1812bf48a66821101492026 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/544ee0cef1812bf48a66821101492026 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread;
static DATA: AtomicU64 = AtomicU64::new(0); // Atomic Data
static READY: AtomicBool = AtomicBool::new(false); // Flag
fn main() {
let _producer = thread::spawn(|| {
// ...Expensive operations captured by Ordering::Release.
DATA.store(123456, Ordering::Relaxed); // Data store here, though relaxed, is covered by Ordering::Release.
READY.store(true, Ordering::Release); // Captures all previous load and store changes before it.
});
// Consumer thread
// Ordering::Acquire loads unto this thread all the changes tracked
// from producer thread.
while !dbg!(READY.load(Ordering::Acquire)) { // Condition will return false.
dbg!(DATA.load(Ordering::Relaxed));
thread::sleep(std::time::Duration::from_millis(500)); // This will not run.
println!("Slept for half a second");
}
dbg!(READY.load(Ordering::Relaxed));
println!("Data: {}", DATA.load(Ordering::Relaxed)); // Guaranteed to be 123456
// producer.join().unwrap(); // Connects the producer thread to the main
// // thread. That way the producer thread does not get orphaned.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment