Using Threads in Rust Programming


We know that a process is a program in a running state. The Operating System maintains and manages multiple processes at once. These processes are run on independent parts and these independent parts are known as threads.

Rust provides an implementation of 1:1 threading. It provides different APIs that handles the case of thread creation, joining, and many such methods.

Creating a new thread with spawn

To create a new thread in Rust, we call the thread::spawn function and then pass it a closure, which in turn contains the code that we want to run in the new thread.

Example

Consider the example shown below:

use std::thread;
use std::time::Duration;

fn main() {
   thread::spawn(|| {
      for i in 1..10 {
         println!("hey number {} from the spawned thread!", i);
         thread::sleep(Duration::from_millis(1));
      }
   });

   for i in 1..3 {
      println!("hey number {} from the main thread!", i);
      thread::sleep(Duration::from_millis(1));
   }
}

Output

hey number 1 from the main thread!
hey number 1 from the spawned thread!
hey number 2 from the main thread!
hey number 2 from the spawned thread!

There are chances that a spawned thread might not run, and to handle that case, we store the value returned from thread::spawn in a variable. The return type of thread::spawn is JoinHandle.

A JoinHandle is an owned value that, when we call the join method on it, will wait for its thread to finish

Example

Let’s modify the example shown above just slightly, like this:

use std::thread;
use std::time::Duration;

fn main() {
   let handle = thread::spawn(|| {
      for i in 1..10 {
         println!("hey number {} from the spawned thread!", i);
         thread::sleep(Duration::from_millis(1));
      }
   });
   handle.join().unwrap();
   for i in 1..5 {
      println!("hey number {} from the main thread!", i);
      thread::sleep(Duration::from_millis(1));
   }
}

Output

hey number 1 from the spawned thread!
hey number 2 from the spawned thread!
hey number 3 from the spawned thread!
hey number 4 from the spawned thread!
hey number 5 from the spawned thread!
hey number 6 from the spawned thread!
hey number 7 from the spawned thread!
hey number 8 from the spawned thread!
hey number 9 from the spawned thread!
hey number 1 from the main thread!
hey number 2 from the main thread!

Updated on: 05-Apr-2021

619 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements