Skip to content

Instantly share code, notes, and snippets.

@maretekent
Forked from therustmonk/control.rs
Created April 24, 2018 17:50
Show Gist options
  • Save maretekent/6ca340fd97b213035713f8957e21d996 to your computer and use it in GitHub Desktop.
Save maretekent/6ca340fd97b213035713f8957e21d996 to your computer and use it in GitHub Desktop.
Rust thread control
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