summaryrefslogtreecommitdiff
path: root/exercises/20_threads/threads1.rs
diff options
context:
space:
mode:
authorAdam Brewer <adamhb321@gmail.com>2023-10-16 07:37:12 -0400
committerAdam Brewer <adamhb321@gmail.com>2023-10-16 07:37:12 -0400
commit64d95837e9813541cf5b357de13865ce687ae98d (patch)
treef022c5d5ba01128811c0b77618a7adb843ee876b /exercises/20_threads/threads1.rs
parentc3941323e2c0b9ee286494327de92e00f23b9e3a (diff)
Update Exercises Directory Names to Reflect Order
Diffstat (limited to 'exercises/20_threads/threads1.rs')
-rw-r--r--exercises/20_threads/threads1.rs40
1 files changed, 40 insertions, 0 deletions
diff --git a/exercises/20_threads/threads1.rs b/exercises/20_threads/threads1.rs
new file mode 100644
index 0000000..80b6def
--- /dev/null
+++ b/exercises/20_threads/threads1.rs
@@ -0,0 +1,40 @@
+// threads1.rs
+//
+// 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.
+
+// I AM NOT DONE
+
+use std::thread;
+use std::time::{Duration, Instant};
+
+fn main() {
+ let mut handles = vec![];
+ for i in 0..10 {
+ 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 results: Vec<u128> = vec![];
+ for handle in handles {
+ // TODO: a struct is returned from thread::spawn, can you use it?
+ }
+
+ 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);
+ }
+}