2018-02-22 13:09:53 +07:00
|
|
|
// threads1.rs
|
2019-11-11 22:51:38 +07:00
|
|
|
// Make this compile! Execute `rustlings hint threads1` for hints :)
|
2021-05-05 08:25:48 +07:00
|
|
|
// The idea is the threads spawned on line 20 are completing jobs while the main thread is
|
2021-05-05 05:49:13 +07:00
|
|
|
// monitoring progress until 10 jobs are completed.
|
2015-09-30 00:39:25 +06:00
|
|
|
|
2019-11-11 19:38:24 +07:00
|
|
|
// I AM NOT DONE
|
|
|
|
|
2015-09-30 00:39:25 +06:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::thread;
|
2016-02-09 03:13:45 +06:00
|
|
|
use std::time::Duration;
|
2015-09-30 00:39:25 +06:00
|
|
|
|
|
|
|
struct JobStatus {
|
|
|
|
jobs_completed: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let status = Arc::new(JobStatus { jobs_completed: 0 });
|
2021-05-05 08:38:18 +07:00
|
|
|
for i in 1..=10 {
|
2021-05-05 05:49:13 +07:00
|
|
|
let status_ref = Arc::clone(&status);
|
|
|
|
thread::spawn(move || {
|
|
|
|
thread::sleep(Duration::from_millis(250 * i));
|
|
|
|
status_ref.jobs_completed += 1;
|
|
|
|
});
|
|
|
|
}
|
2015-09-30 00:39:25 +06:00
|
|
|
while status.jobs_completed < 10 {
|
2021-05-05 05:49:13 +07:00
|
|
|
println!("waiting for {} jobs ({} jobs running)... ",
|
|
|
|
(10 - status.jobs_completed),
|
|
|
|
(Arc::strong_count(&status) - 1) // subtract one for refrence in _this_ thread
|
|
|
|
);
|
2016-02-09 03:13:45 +06:00
|
|
|
thread::sleep(Duration::from_millis(500));
|
2015-09-30 00:39:25 +06:00
|
|
|
}
|
|
|
|
}
|