Forem

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.
/*
Copyright (c) 2023
Author : Bruno Capuano
Create Time : 2023 January
Change Log :
- Demos working with threads in Rust
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
println!(" >> Begin thread work, wait 5 seconds ...");
thread::sleep(Duration::from_millis(5000));
println!(" >> End thread work ...");
});
for i in 0..5 {
println!("Loop 1 iteration: {}", i);
thread::sleep(Duration::from_millis(500));
}
}

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.

/*
Copyright (c) 2023
Author : Bruno Capuano
Create Time : 2023 January
Change Log :
- Demos working with threads in Rust
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
use std::thread;
use std::time::Duration;
fn main() {
let sec_thread = thread::spawn(|| {
println!(" >> Begin thread work, wait 5 seconds ...");
thread::sleep(Duration::from_millis(5000));
println!(" >> End thread work ...");
});
for i in 0..5 {
println!("Loop 1 iteration: {}", i);
thread::sleep(Duration::from_millis(500));
}
sec_thread.join().unwrap();
}

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site