Skip to content

Commit 458f30e

Browse files
committed
Modify code Move handle join before final loop so print are not interleaved
1 parent 9c99742 commit 458f30e

File tree

2 files changed

+68
-3
lines changed

2 files changed

+68
-3
lines changed

documentation2/B09-Thread.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,68 @@ cargo run
138138
8 from the spawned thread!
139139
9 from the spawned thread!
140140
```
141+
142+
Here, we save the return of the `thread::spawn()` function and bind it to a variable called `handle`.
143+
144+
In the final line of the code, we call the `join()` method of the `handle`. Calling `join()` on the `handle` blocks the thread until the thread terminates.
145+
146+
The two threads (main and spawned thread) continue alternating for some time, but the main thread waits because of `handle.join()` and does not end until the spawned thread is finished.
147+
148+
____
149+
150+
If we move the `handle.join()` before the final loop, the output will change and the print statements won't be interleaved.
151+
152+
____
153+
154+
```rust
155+
use std::thread;
156+
use std::time::Duration;
157+
158+
fn main() {
159+
// create a thread and save the handle to a variable
160+
let handle = thread::spawn(|| {
161+
// everything in here runs in a separate thread
162+
for i in 0..10 {
163+
println!("{} from the spawned thread!", i);
164+
thread::sleep(Duration::from_millis(2));
165+
}
166+
});
167+
168+
// wait for the separate thread to complete
169+
handle.join().unwrap();
170+
171+
// main thread
172+
for i in 0..5 {
173+
println!("{} from the main thread!", i);
174+
thread::sleep(Duration::from_millis(1));
175+
}
176+
}
177+
```
178+
179+
```bash
180+
cargo build
181+
```
182+
183+
```bash
184+
cargo run
185+
```
186+
187+
##### Output of latest code
188+
189+
```bash
190+
0 from the spawned thread!
191+
1 from the spawned thread!
192+
2 from the spawned thread!
193+
3 from the spawned thread!
194+
4 from the spawned thread!
195+
5 from the spawned thread!
196+
6 from the spawned thread!
197+
7 from the spawned thread!
198+
8 from the spawned thread!
199+
9 from the spawned thread!
200+
0 from the main thread!
201+
1 from the main thread!
202+
2 from the main thread!
203+
3 from the main thread!
204+
4 from the main thread!
205+
```

programiz/attempt-02/hello_world/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@ fn main() {
1010
thread::sleep(Duration::from_millis(2));
1111
}
1212
});
13+
14+
// wait for the separate thread to complete
15+
handle.join().unwrap();
1316

1417
// main thread
1518
for i in 0..5 {
1619
println!("{} from the main thread!", i);
1720
thread::sleep(Duration::from_millis(1));
1821
}
19-
20-
// wait for the separate thread to complete
21-
handle.join().unwrap();
2222
}

0 commit comments

Comments
 (0)