|
1 | 1 | // threads1.rs
|
2 | 2 | // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a hint.
|
3 |
| -// This program should wait until all the spawned threads have finished before exiting. |
| 3 | + |
| 4 | +// This program spawns multiple threads that each run for at least 250ms, |
| 5 | +// and each thread returns how much time they took to complete. |
| 6 | +// The program should wait until all the spawned threads have finished and |
| 7 | +// should collect their return values into a vector. |
4 | 8 |
|
5 | 9 | // I AM NOT DONE
|
6 | 10 |
|
7 | 11 | use std::thread;
|
8 |
| -use std::time::Duration; |
9 |
| - |
| 12 | +use std::time::{Duration, Instant}; |
10 | 13 |
|
11 | 14 | fn main() {
|
12 |
| - |
13 | 15 | let mut handles = vec![];
|
14 | 16 | for i in 0..10 {
|
15 |
| - thread::spawn(move || { |
| 17 | + handles.push(thread::spawn(move || { |
| 18 | + let start = Instant::now(); |
16 | 19 | thread::sleep(Duration::from_millis(250));
|
17 | 20 | println!("thread {} is complete", i);
|
18 |
| - }); |
| 21 | + start.elapsed().as_millis() |
| 22 | + })); |
19 | 23 | }
|
20 | 24 |
|
21 |
| - let mut completed_threads = 0; |
| 25 | + let mut results: Vec<u128> = vec![]; |
22 | 26 | for handle in handles {
|
23 | 27 | // TODO: a struct is returned from thread::spawn, can you use it?
|
24 |
| - completed_threads += 1; |
25 | 28 | }
|
26 | 29 |
|
27 |
| - if completed_threads != 10 { |
| 30 | + if results.len() != 10 { |
28 | 31 | panic!("Oh no! All the spawned threads did not finish!");
|
29 | 32 | }
|
30 | 33 |
|
| 34 | + println!(); |
| 35 | + for (i, result) in results.into_iter().enumerate() { |
| 36 | + println!("thread {} took {}ms", i, result); |
| 37 | + } |
31 | 38 | }
|
0 commit comments