rustlings/exercises/threads/threads1.rs
Donald Guy 791120c0c1
threads1: use more threads, model more reference counting
- Switch from a single additional thread (receiving/holding a single `Arc::clone` reference) running a loop modeling 10 sequential jobs, to a loop generating 10 threads each modeling 1 job (each getting their own `Arc::clone` reference)
- use the previously ignored `for` loop var to keep the execution timing approx the same
- Print a more descriptive waiting message (taking an opportunity to use comment to disambiguate the count)
2021-05-04 18:49:13 -04:00

33 lines
954 B
Rust

// threads1.rs
// Make this compile! Execute `rustlings hint threads1` for hints :)
// The idea is the threads spawned on line 22 are completing jobs while the main thread is
// monitoring progress until 10 jobs are completed.
// I AM NOT DONE
use std::sync::Arc;
use std::thread;
use std::time::Duration;
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
for i in 0..10 {
let status_ref = Arc::clone(&status);
thread::spawn(move || {
thread::sleep(Duration::from_millis(250 * i));
status_ref.jobs_completed += 1;
});
}
while status.jobs_completed < 10 {
println!("waiting for {} jobs ({} jobs running)... ",
(10 - status.jobs_completed),
(Arc::strong_count(&status) - 1) // subtract one for refrence in _this_ thread
);
thread::sleep(Duration::from_millis(500));
}
}