2018-02-22 08:09:53 +02:00
|
|
|
// threads1.rs
|
2023-05-29 19:39:08 +02:00
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
//
|
|
|
|
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
|
|
|
|
// hint.
|
2015-09-29 20:39:25 +02:00
|
|
|
|
2019-11-11 14:38:24 +02:00
|
|
|
// I AM NOT DONE
|
|
|
|
|
2015-09-29 20:39:25 +02:00
|
|
|
use std::thread;
|
2022-12-26 10:25:43 +02:00
|
|
|
use std::time::{Duration, Instant};
|
2015-09-29 20:39:25 +02:00
|
|
|
|
|
|
|
fn main() {
|
2021-12-23 16:19:39 +02:00
|
|
|
let mut handles = vec![];
|
|
|
|
for i in 0..10 {
|
2022-12-26 10:25:43 +02:00
|
|
|
handles.push(thread::spawn(move || {
|
|
|
|
let start = Instant::now();
|
2016-02-08 23:13:45 +02:00
|
|
|
thread::sleep(Duration::from_millis(250));
|
2021-12-23 16:19:39 +02:00
|
|
|
println!("thread {} is complete", i);
|
2022-12-26 10:25:43 +02:00
|
|
|
start.elapsed().as_millis()
|
|
|
|
}));
|
2021-12-23 16:19:39 +02:00
|
|
|
}
|
|
|
|
|
2022-12-26 10:25:43 +02:00
|
|
|
let mut results: Vec<u128> = vec![];
|
2021-12-23 16:19:39 +02:00
|
|
|
for handle in handles {
|
|
|
|
// TODO: a struct is returned from thread::spawn, can you use it?
|
|
|
|
}
|
|
|
|
|
2022-12-26 10:25:43 +02:00
|
|
|
if results.len() != 10 {
|
2021-12-23 16:19:39 +02:00
|
|
|
panic!("Oh no! All the spawned threads did not finish!");
|
2015-09-29 20:39:25 +02:00
|
|
|
}
|
2023-03-31 11:20:11 +02:00
|
|
|
|
2022-12-26 10:25:43 +02:00
|
|
|
println!();
|
|
|
|
for (i, result) in results.into_iter().enumerate() {
|
|
|
|
println!("thread {} took {}ms", i, result);
|
|
|
|
}
|
2015-09-29 20:39:25 +02:00
|
|
|
}
|