-
-
Save allwelldotdev/0628f2ca248ab6c6dc7d8ce8bfbe149f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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