2024-10-22 06:49:44 +01: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
|
2024-07-01 09:59:33 +01:00
|
|
|
// wait until all the spawned threads have finished and should collect their
|
|
|
|
// return values into a vector.
|
|
|
|
|
|
|
|
use std::{
|
|
|
|
thread,
|
|
|
|
time::{Duration, Instant},
|
|
|
|
};
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let mut handles = Vec::new();
|
|
|
|
for i in 0..10 {
|
|
|
|
let handle = thread::spawn(move || {
|
|
|
|
let start = Instant::now();
|
|
|
|
thread::sleep(Duration::from_millis(250));
|
|
|
|
println!("Thread {i} done");
|
|
|
|
start.elapsed().as_millis()
|
|
|
|
});
|
|
|
|
handles.push(handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut results = Vec::new();
|
|
|
|
for handle in handles {
|
|
|
|
// Collect the results of all threads into the `results` vector.
|
|
|
|
results.push(handle.join().unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
if results.len() != 10 {
|
|
|
|
panic!("Oh no! Some thread isn't done yet!");
|
|
|
|
}
|
|
|
|
|
|
|
|
println!();
|
|
|
|
for (i, result) in results.into_iter().enumerate() {
|
|
|
|
println!("Thread {i} took {result}ms");
|
|
|
|
}
|
|
|
|
}
|