This commit is contained in:
Donald Guy 2021-07-05 16:26:26 -07:00 committed by GitHub
commit dad963fbb8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,10 +1,7 @@
// threads1.rs
// Make this compile! Execute `rustlings hint threads1` for hints :)
// The idea is the thread spawned on line 22 is completing jobs while the main thread is
// monitoring progress until 10 jobs are completed. Because of the difference between the
// spawned threads' sleep time, and the waiting threads sleep time, when you see 6 lines
// of "waiting..." and the program ends without timing out when running,
// you've got it :)
// The idea is the threads spawned on line 20 are completing jobs while the main thread is
// monitoring progress until 10 jobs are completed.
// I AM NOT DONE
@ -18,15 +15,18 @@ struct JobStatus {
fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
let status_shared = status.clone();
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
status_shared.jobs_completed += 1;
}
});
for i in 1..=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... ");
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));
}
}