Hi !
Let’s take a look at the following code.
- The main thread will run a loop for ~5 seconds, displaying a message every 1 second.
- The 2nd thread with display a message, wait 5 seconds and display a 2nd message.
The code output shows that the app is closed before finishing the execution of the 2nd thread.
Joining thread handles
When we work in multi-threading scenarios, the previous problem is solved joining threads (joining thread handles). We need to join the 2nd thread and the main thread.
In order to do this, we just assign the 2nd thread to a variable.
let sec_thread = thread::spawn(|| { ...
And to join the handles we use the .join().unwrap() method.
Note: unwrap() will help us handle possible errors.
The full code looks like this.
And we have the expected output.
In next posts, more about threads in Rust.
Happy coding!
Greetings
El Bruno
More posts in my blog ElBruno.com.