Created
July 30, 2019 19:26
-
-
Save fcracker79/2a895137b8874a40d4bd4854a7f509be to your computer and use it in GitHub Desktop.
Control multiple threads
This file contains 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::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