Skip to content

Commit 498c73b

Browse files
committed
Add example of Using move Closures with Threads
1 parent 458f30e commit 498c73b

File tree

2 files changed

+50
-17
lines changed

2 files changed

+50
-17
lines changed

documentation2/B09-Thread.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,3 +203,44 @@ cargo run
203203
3 from the main thread!
204204
4 from the main thread!
205205
```
206+
207+
Thus, it is important to know where `join()` is called. I will dictate whether threads run at the same time or not.
208+
209+
____
210+
211+
### Using move Closures with Threads in Rust
212+
213+
A value can be moved into a separate thread by passing it as an argument to the `thread::spawn()` function.
214+
215+
Let's look at an example.
216+
217+
```rust
218+
use std::thread;
219+
220+
fn main() {
221+
// main thread starts here
222+
let message = String::from("Hello, World!");
223+
224+
// move the message value to a separate thread
225+
let handle = thread::spawn(move || {
226+
println!("{}", message);
227+
});
228+
229+
// wait for the thread to finish
230+
handle.join().unwrap();
231+
}
232+
```
233+
234+
```bash
235+
cargo build
236+
```
237+
238+
```bash
239+
cargo run
240+
```
241+
242+
#### Output
243+
244+
```bash
245+
Hello, World!
246+
```
Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,14 @@
11
use std::thread;
2-
use std::time::Duration;
32

43
fn main() {
5-
// create a thread and save the handle to a variable
6-
let handle = thread::spawn(|| {
7-
// everything in here runs in a separate thread
8-
for i in 0..10 {
9-
println!("{} from the spawned thread!", i);
10-
thread::sleep(Duration::from_millis(2));
11-
}
4+
// main thread starts here
5+
let message = String::from("Hello, World!");
6+
7+
// move the message value to a separate thread
8+
let handle = thread::spawn(move || {
9+
println!("{}", message);
1210
});
13-
14-
// wait for the separate thread to complete
15-
handle.join().unwrap();
1611

17-
// main thread
18-
for i in 0..5 {
19-
println!("{} from the main thread!", i);
20-
thread::sleep(Duration::from_millis(1));
21-
}
22-
}
12+
// wait for the thread to finish
13+
handle.join().unwrap();
14+
}

0 commit comments

Comments
 (0)