Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.