summaryrefslogtreecommitdiff
path: root/solutions/20_threads/threads1.rs
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
committermo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
commit7123c7ae3a9605fbe962e4ef0a0f1424cd16fef8 (patch)
treec67f7e62bb9a179ae4fdbab492501cb6847e64c7 /solutions/20_threads/threads1.rs
parent77b687d501771c24bd83294d97b8e6f9ffa92d6b (diff)
parent4d9c346a173bb722b929f3ea3c00f84954483e24 (diff)
Merge remote-tracking branch 'upstream/main' into fix-enum-variant-inconsistency
Diffstat (limited to 'solutions/20_threads/threads1.rs')
-rw-r--r--solutions/20_threads/threads1.rs37
1 files changed, 37 insertions, 0 deletions
diff --git a/solutions/20_threads/threads1.rs b/solutions/20_threads/threads1.rs
new file mode 100644
index 0000000..7f3dd29
--- /dev/null
+++ b/solutions/20_threads/threads1.rs
@@ -0,0 +1,37 @@
+// 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.
+
+use std::{
+ thread,
+ time::{Duration, Instant},
+};
+
+fn main() {
+ let mut handles = Vec::new();
+ for i in 0..10 {
+ let handle = thread::spawn(move || {
+ let start = Instant::now();
+ thread::sleep(Duration::from_millis(250));
+ println!("Thread {i} done");
+ start.elapsed().as_millis()
+ });
+ handles.push(handle);
+ }
+
+ let mut results = Vec::new();
+ for handle in handles {
+ // Collect the results of all threads into the `results` vector.
+ results.push(handle.join().unwrap());
+ }
+
+ if results.len() != 10 {
+ panic!("Oh no! Some thread isn't done yet!");
+ }
+
+ println!();
+ for (i, result) in results.into_iter().enumerate() {
+ println!("Thread {i} took {result}ms");
+ }
+}