Skip to content

Instantly share code, notes, and snippets.

@allwelldotdev
Forked from rust-play/playground.rs
Last active October 14, 2025 09:11
Show Gist options
  • Select an option

  • Save allwelldotdev/0628f2ca248ab6c6dc7d8ce8bfbe149f to your computer and use it in GitHub Desktop.

Select an option

Save allwelldotdev/0628f2ca248ab6c6dc7d8ce8bfbe149f 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