DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

#Rust 🦀 – Working with threads 🧵 and joining thread handles

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.

main thread will run and stop, even if the 2ndary thread is still running.

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(|| { ...

Enter fullscreen mode Exit fullscreen mode

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.

joining threads in Rust

In next posts, more about threads in Rust.
Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.

Top comments (0)