rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

threads2.rs (1007B)


      1 // Building on the last exercise, we want all of the threads to complete their
      2 // work. But this time, the spawned threads need to be in charge of updating a
      3 // shared value: `JobStatus.jobs_done`
      4 
      5 use std::{sync::Arc, thread, time::Duration};
      6 
      7 struct JobStatus {
      8     jobs_done: u32,
      9 }
     10 
     11 fn main() {
     12     // TODO: `Arc` isn't enough if you want a **mutable** shared state.
     13     let status = Arc::new(JobStatus { jobs_done: 0 });
     14 
     15     let mut handles = Vec::new();
     16     for _ in 0..10 {
     17         let status_shared = Arc::clone(&status);
     18         let handle = thread::spawn(move || {
     19             thread::sleep(Duration::from_millis(250));
     20 
     21             // TODO: You must take an action before you update a shared value.
     22             status_shared.jobs_done += 1;
     23         });
     24         handles.push(handle);
     25     }
     26 
     27     // Waiting for all jobs to complete.
     28     for handle in handles {
     29         handle.join().unwrap();
     30     }
     31 
     32     // TODO: Print the value of `JobStatus.jobs_done`.
     33     println!("Jobs done: {}", todo!());
     34 }