Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcracker79/2a895137b8874a40d4bd4854a7f509be to your computer and use it in GitHub Desktop.
Save fcracker79/2a895137b8874a40d4bd4854a7f509be to your computer and use it in GitHub Desktop.
Control multiple threads
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() {
let ref_counter = Arc::new(true);
for i in 0..10 {
let cur_ref_counter = Arc::clone(&ref_counter);
thread::spawn(move || {
thread::sleep(Duration::from_secs(i + 1));
cur_ref_counter;
println!("Thread {} is dying!", i);
});
}
loop {
let count = Arc::strong_count(&ref_counter) - 1;
println!("Current living threads: {}", count);
if count == 0 {
println!("All threads are gone!");
break;
}
thread::sleep(Duration::from_millis(200));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment