rustlings/exercises/20_threads/threads1.rs

38 lines
1.1 KiB
Rust
Raw Normal View History

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