You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation2/B09-Thread.md
+65Lines changed: 65 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -138,3 +138,68 @@ cargo run
138
138
8 from the spawned thread!
139
139
9 from the spawned thread!
140
140
```
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
+
usestd::thread;
156
+
usestd::time::Duration;
157
+
158
+
fnmain() {
159
+
// create a thread and save the handle to a variable
0 commit comments