summaryrefslogtreecommitdiff
path: root/exercises/20_threads
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-07-01 10:59:33 +0200
committermo8it <mo8it@proton.me>2024-07-01 10:59:33 +0200
commitb000164eedaf5ada18ce0562aa9b7aed25663458 (patch)
treeb6da90b523f1e319b43e111fcf3c6d0d5614f7a7 /exercises/20_threads
parent663a03a17b2d2001f4f3f35a59cd2e2aa5f2bb24 (diff)
threads1 solution
Diffstat (limited to 'exercises/20_threads')
-rw-r--r--exercises/20_threads/threads1.rs24
1 files changed, 14 insertions, 10 deletions
diff --git a/exercises/20_threads/threads1.rs b/exercises/20_threads/threads1.rs
index bf0b8e0..01f9ff4 100644
--- a/exercises/20_threads/threads1.rs
+++ b/exercises/20_threads/threads1.rs
@@ -3,31 +3,35 @@
// wait until all the spawned threads have finished and should collect their
// return values into a vector.
-use std::thread;
-use std::time::{Duration, Instant};
+use std::{
+ thread,
+ time::{Duration, Instant},
+};
fn main() {
- let mut handles = vec![];
+ let mut handles = Vec::new();
for i in 0..10 {
- handles.push(thread::spawn(move || {
+ let handle = thread::spawn(move || {
let start = Instant::now();
thread::sleep(Duration::from_millis(250));
- println!("thread {} is complete", i);
+ println!("Thread {i} done");
start.elapsed().as_millis()
- }));
+ });
+ handles.push(handle);
}
- let mut results: Vec<u128> = vec![];
+ let mut results = Vec::new();
for handle in handles {
- // TODO: a struct is returned from thread::spawn, can you use it?
+ // 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 {
- panic!("Oh no! All the spawned threads did not finish!");
+ panic!("Oh no! Some thread isn't done yet!");
}
println!();
for (i, result) in results.into_iter().enumerate() {
- println!("thread {} took {}ms", i, result);
+ println!("Thread {i} took {result}ms");
}
}