-
-
Save maretekent/6ca340fd97b213035713f8957e21d996 to your computer and use it in GitHub Desktop.
Rust thread control
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::time::Duration; | |
use std::sync::Arc; | |
use std::sync::atomic::{AtomicBool, Ordering}; | |
use std::thread; | |
fn main() { | |
// Play with this flag | |
let fatal_flag = true; | |
let do_stop = true; | |
let working = Arc::new(AtomicBool::new(true)); | |
let control = Arc::downgrade(&working); | |
thread::spawn(move || { | |
while (*working).load(Ordering::Relaxed) { | |
if fatal_flag { | |
panic!("Oh, my God!"); | |
} else { | |
thread::sleep(Duration::from_millis(20)); | |
println!("I'm alive!"); | |
} | |
} | |
}); | |
thread::sleep(Duration::from_millis(50)); | |
if do_stop { | |
// To stop thread | |
match control.upgrade() { | |
Some(working) => (*working).store(false, Ordering::Relaxed), | |
None => println!("Sorry, but thread has died."), | |
} | |
} | |
thread::sleep(Duration::from_millis(50)); | |
match control.upgrade() { | |
Some(_) => println!("Thread alive!"), | |
None => println!("Thread ends!"), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment