threads2.rs - comment and hint for Mutex
In 1st line of main (line 17) there is this:
let status = Arc::new(JobStatus { jobs_completed: 0 });
Since all exercises outlines a todo, maybe a TODO comment should be added here for hint to adding Mutex.
Another comment on possible solution. I also like using while loop instead of using handles. It made me understand locking a bit better and that after each loop, status is unlocked, so that next sub thread can lock it and then lock again in next while loop - if I understand this correct :).
// solution 1 using locked status in a while do loop // using lock in loop and implicitly unlocking it allows next sub thread taking control of status. for i in 0..10 { let status_shared = status.clone(); thread::spawn(move || { // use i so that each job starts 250ms later... thread::sleep(Duration::from_millis(i * 250 + 250)); // TODO: You must take an action before you update a shared value status_shared.lock().unwrap().jobs_completed += 1; }); } while status.lock().unwrap().jobs_completed < 10 { println!("Waiting for job {}", status.to_owned().lock().unwrap().jobs_completed); thread::sleep(Duration::from_millis(250)); } println!("Jobs completed: {}", status.to_owned().lock().unwrap().jobs_completed);
In either case I would use counter for calculating thread sleep duration (as shown in above example). This makes output look better:
... for i in 0..10 { ... thread::sleep(Duration::from_millis(i * 250 + 250)); ... for handle in handles { ... println!("jobs completed {}", status.lock().unwrap().jobs_completed); } ...
Output:
jobs completed 1 jobs completed 2 jobs completed 3 jobs completed 4 jobs completed 5 jobs completed 6 jobs completed 7 jobs completed 8 jobs completed 9 jobs completed 10
====================
In either case I would use counter for calculating thread sleep duration (as shown in above example). This makes output look better:
... for i in 0..10 { ... thread::sleep(Duration::from_millis(i * 250 + 250)); ... for handle in handles { ... println!("jobs completed {}", status.lock().unwrap().jobs_completed); } ...
Output:
jobs completed 1 jobs completed 2 jobs completed 3 jobs completed 4 jobs completed 5 jobs completed 6 jobs completed 7 jobs completed 8 jobs completed 9 jobs completed 10
====================
I was wondering why it always printed "jobs completed 10"