diff options
| author | Emmanuel Roullit <eroullit@github.com> | 2023-02-25 17:11:43 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-02-25 17:11:43 +0100 |
| commit | fcadbfc70d578e4a993711d5a7f1737aebd6b3ce (patch) | |
| tree | 897142c1904755a43aefce56695c0b8186381e69 /exercises/threads/threads1.rs | |
| parent | b653d4848a52701d2240f130ab74c158dd5d7069 (diff) | |
| parent | 701b4bef51b50d1fd3bb7fbfe3cc274f2bbdcb0c (diff) | |
Merge branch 'rust-lang:main' into codespaces
Diffstat (limited to 'exercises/threads/threads1.rs')
| -rw-r--r-- | exercises/threads/threads1.rs | 25 |
1 files changed, 16 insertions, 9 deletions
diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index e59f4ce..d6376db 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -1,31 +1,38 @@ // threads1.rs // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a hint. -// This program should wait until all the spawned threads have finished before exiting. + +// 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. // I AM NOT DONE use std::thread; -use std::time::Duration; - +use std::time::{Duration, Instant}; fn main() { - let mut handles = vec![]; for i in 0..10 { - thread::spawn(move || { + handles.push(thread::spawn(move || { + let start = Instant::now(); thread::sleep(Duration::from_millis(250)); println!("thread {} is complete", i); - }); + start.elapsed().as_millis() + })); } - let mut completed_threads = 0; + let mut results: Vec<u128> = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? - completed_threads += 1; } - if completed_threads != 10 { + if results.len() != 10 { panic!("Oh no! All the spawned threads did not finish!"); } + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("thread {} took {}ms", i, result); + } } |
