complete: threads

This commit is contained in:
seth 2021-06-25 10:54:32 +08:00
parent d6490f118b
commit e5954bbb2b

View file

@ -6,9 +6,7 @@
// of "waiting..." and the program ends without timing out when running, // of "waiting..." and the program ends without timing out when running,
// you've got it :) // you've got it :)
// I AM NOT DONE use std::sync::{Mutex, Arc};
use std::sync::Arc;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -17,15 +15,15 @@ struct JobStatus {
} }
fn main() { fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 }); let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone(); let status_shared = Arc::clone(&status);
thread::spawn(move || { thread::spawn(move || {
for _ in 0..10 { for _ in 0..10 {
thread::sleep(Duration::from_millis(250)); thread::sleep(Duration::from_millis(250));
status_shared.jobs_completed += 1; status_shared.lock().unwrap().jobs_completed += 1;
} }
}); });
while status.jobs_completed < 10 { while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... "); println!("waiting... ");
thread::sleep(Duration::from_millis(500)); thread::sleep(Duration::from_millis(500));
} }