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
+75Lines changed: 75 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -63,3 +63,78 @@ cargo run
63
63
4 from the main thread!
64
64
3 from the spawned thread!
65
65
```
66
+
67
+
In the example above, we create a thread using the `thread::spawn()` function. The thread loops over `0..5` and prints the current value.
68
+
69
+
Similarly, we have a main thread where we loop over `0..5` and print the current value.
70
+
71
+
We also call `thread::sleep` to force a thread to stop its execution for a short duration, allowing a different thread to run.
72
+
73
+
Notice that we sleep **2** milliseconds in the spawned thread and 1 millisecond in the main thread.
74
+
75
+
The output from this program might be a little different every time. The important thing to remember here is that if the main thread completes, all other threads are shut down whether or not they have finished running.
76
+
77
+
So, even though the spawned thread should print until `i` is 9, it only reaches to **2** because the main thread shut down.
78
+
79
+
____
80
+
81
+
### Join Handles in Rust
82
+
83
+
A spawned thread always returns a join handle. If we want the spawned thread to complete execution, we can save the return value of `thread::spawn` in a variable and then call the `join()` method on it.
84
+
85
+
The `join()` method on `JoinHandle` (return type of `thread::spawn`) waits for the spawned thread to finish.
86
+
87
+
Let's look at an example.
88
+
89
+
```rust
90
+
usestd::thread;
91
+
usestd::time::Duration;
92
+
93
+
fnmain() {
94
+
// create a thread and save the handle to a variable
0 commit comments