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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leave a comment