File tree Expand file tree Collapse file tree 2 files changed +50
-17
lines changed
programiz/attempt-02/hello_world/src Expand file tree Collapse file tree 2 files changed +50
-17
lines changed Original file line number Diff line number Diff line change @@ -203,3 +203,44 @@ cargo run
2032033 from the main thread!
2042044 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+ ```
Original file line number Diff line number Diff line change 11use std:: thread;
2- use std:: time:: Duration ;
32
43fn 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+ }
You can’t perform that action at this time.
0 commit comments