2024-10-22 01:49:44 -04:00
|
|
|
// This program spawns multiple threads that each runs for at least 250ms, and
|
|
|
|
// each thread returns how much time it took to complete. The program should
|
2023-05-29 13:39:08 -04:00
|
|
|
// wait until all the spawned threads have finished and should collect their
|
|
|
|
// return values into a vector.
|
2015-09-29 14:39:25 -04:00
|
|
|
|
2024-07-01 04:59:33 -04:00
|
|
|
use std::{
|
|
|
|
thread,
|
|
|
|
time::{Duration, Instant},
|
|
|
|
};
|
2015-09-29 14:39:25 -04:00
|
|
|
|
|
|
|
fn main() {
|
2024-07-01 04:59:33 -04:00
|
|
|
let mut handles = Vec::new();
|
2021-12-23 09:19:39 -05:00
|
|
|
for i in 0..10 {
|
2024-07-01 04:59:33 -04:00
|
|
|
let handle = thread::spawn(move || {
|
2022-12-26 03:25:43 -05:00
|
|
|
let start = Instant::now();
|
2016-02-08 16:13:45 -05:00
|
|
|
thread::sleep(Duration::from_millis(250));
|
2024-07-01 04:59:33 -04:00
|
|
|
println!("Thread {i} done");
|
2022-12-26 03:25:43 -05:00
|
|
|
start.elapsed().as_millis()
|
2024-07-01 04:59:33 -04:00
|
|
|
});
|
|
|
|
handles.push(handle);
|
2021-12-23 09:19:39 -05:00
|
|
|
}
|
|
|
|
|
2024-07-01 04:59:33 -04:00
|
|
|
let mut results = Vec::new();
|
2021-12-23 09:19:39 -05:00
|
|
|
for handle in handles {
|
2024-07-01 04:59:33 -04:00
|
|
|
// TODO: Collect the results of all threads into the `results` vector.
|
|
|
|
// Use the `JoinHandle` struct which is returned by `thread::spawn`.
|
2021-12-23 09:19:39 -05:00
|
|
|
}
|
|
|
|
|
2022-12-26 03:25:43 -05:00
|
|
|
if results.len() != 10 {
|
2024-07-01 04:59:33 -04:00
|
|
|
panic!("Oh no! Some thread isn't done yet!");
|
2015-09-29 14:39:25 -04:00
|
|
|
}
|
2023-03-31 05:20:11 -04:00
|
|
|
|
2022-12-26 03:25:43 -05:00
|
|
|
println!();
|
|
|
|
for (i, result) in results.into_iter().enumerate() {
|
2024-07-01 04:59:33 -04:00
|
|
|
println!("Thread {i} took {result}ms");
|
2022-12-26 03:25:43 -05:00
|
|
|
}
|
2015-09-29 14:39:25 -04:00
|
|
|
}
|