Hi !
In order to access external variables in a thread, we must use the move closure with the move keyword in the thread creation.
In example, these 2 lines will define and create a mutable variable and then a new thread where we can access the var.
let mut new_var = "hey!";
let handle =thread::spawn(move || {
// access to new_var here
})
And an example of the previous code will have:
- A main thread where we declare a string var with a message.
- The 2nd thread that will display a message using the main thread message.
The code output shows that the app is closed before finishing the execution of the 2nd thread.
Super cool !
Happy coding!
Greetings
El Bruno
More posts in my blog ElBruno.com.
Top comments (0)