Skip to content

Commit 7e4ce38

Browse files
committed
fix(threads1): make program panic if threads are not joined
closes #1298
1 parent 32b234c commit 7e4ce38

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

exercises/threads/threads1.rs

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,38 @@
11
// threads1.rs
22
// 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.
48

59
// I AM NOT DONE
610

711
use std::thread;
8-
use std::time::Duration;
9-
12+
use std::time::{Duration, Instant};
1013

1114
fn main() {
12-
1315
let mut handles = vec![];
1416
for i in 0..10 {
15-
thread::spawn(move || {
17+
handles.push(thread::spawn(move || {
18+
let start = Instant::now();
1619
thread::sleep(Duration::from_millis(250));
1720
println!("thread {} is complete", i);
18-
});
21+
start.elapsed().as_millis()
22+
}));
1923
}
2024

21-
let mut completed_threads = 0;
25+
let mut results: Vec<u128> = vec![];
2226
for handle in handles {
2327
// TODO: a struct is returned from thread::spawn, can you use it?
24-
completed_threads += 1;
2528
}
2629

27-
if completed_threads != 10 {
30+
if results.len() != 10 {
2831
panic!("Oh no! All the spawned threads did not finish!");
2932
}
3033

34+
println!();
35+
for (i, result) in results.into_iter().enumerate() {
36+
println!("thread {} took {}ms", i, result);
37+
}
3138
}

info.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -969,7 +969,7 @@ A challenge with multi-threaded applications is that the main thread can
969969
finish before the spawned threads are completed.
970970
https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish-using-join-handles
971971
972-
Collect the JoinHandles and wait for them to finish.
972+
Use the JoinHandles to wait for each thread to finish and collect their results.
973973
https://doc.rust-lang.org/std/thread/struct.JoinHandle.html
974974
"""
975975

0 commit comments

Comments
 (0)