rustlings

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

threads1.rs (1105B)


      1 // This program spawns multiple threads that each runs for at least 250ms, and
      2 // each thread returns how much time it took to complete. The program should
      3 // wait until all the spawned threads have finished and should collect their
      4 // return values into a vector.
      5 
      6 use std::{
      7     thread,
      8     time::{Duration, Instant},
      9 };
     10 
     11 fn main() {
     12     let mut handles = Vec::new();
     13     for i in 0..10 {
     14         let handle = thread::spawn(move || {
     15             let start = Instant::now();
     16             thread::sleep(Duration::from_millis(250));
     17             println!("Thread {i} done");
     18             start.elapsed().as_millis()
     19         });
     20         handles.push(handle);
     21     }
     22 
     23     let mut results = Vec::new();
     24     for handle in handles {
     25         // TODO: Collect the results of all threads into the `results` vector.
     26         // Use the `JoinHandle` struct which is returned by `thread::spawn`.
     27     }
     28 
     29     if results.len() != 10 {
     30         panic!("Oh no! Some thread isn't done yet!");
     31     }
     32 
     33     println!();
     34     for (i, result) in results.into_iter().enumerate() {
     35         println!("Thread {i} took {result}ms");
     36     }
     37 }