Concurrency in Rust is indeed fearless

Reading Time: 3 minutes

In modern operating systems, the executed program’s code is run in a process, and the operating system manages multiple processes at once. Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads.

A thread is a part of the process that runs along with the main process using a technique called context-switching. So, we can create a thread in Rust and implement concurrency in our program.

Dividing your program into multiple threads is a good idea but it increases a lot of complexity to our code. This is due to the fact that threads can run simultaneously, so there’s no guarantee about the order in which the parts of your code on different threads will run. This can lead to problems like Race conditions, Deadlocks, etc. Rust provides features to reduce the negative effects of threads.

Rust (programming language) - Wikipedia

Creating a New Thread with spawn

Now that we know about threads and how they work, we will now see how we can define threads in Rust. We can create a thread in Rust using thread::spawn function. We pass a closure to this function containing the code we want to run as a thread.

Below is an example showing how can we create a thread in Rust and how they are executed.

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

fn main() {
    thread::spawn(|| {
        for _index in 1..10 {
            println!("in spawned thread");
            thread::sleep(Duration::from_millis(1));
        }
    });

    for _index in 1..5 {
        println!("in main thread");
        thread::sleep(Duration::from_millis(1));
    }
}

The calls to thread::sleep force a thread to stop its execution for a short duration, allowing a different thread to run. When we compile this code we get the following output.

in main thread
in spawned thread
in main thread
in spawned thread
in main thread
in spawned thread
in main thread
in spawned thread
in spawned thread

As you can see that the order in which the threads are executed cannot be predicted. But the thing worth noticing is that when the main thread ended, it also stopped the execution of the spawned thread that we created. The “in spawned thread” message was printed 5 times, but the loop was for 10 times. This is not desirable as it abruptly shuts down our spawned thread leading to problems.

Waiting for All Threads to Finish Using join Handles

As we saw in the previous example that our spawned thread did not execute completely. On the other hand, it stopped as soon as our main thread stopped. We can fix this problem by storing the return value of thread::spawn in a variable. The return type of thread::spawn is JoinHandle. A JoinHandle is an owned value that will wait for its thread to finish when we call the join method on it.

For more clarity, look at the example given below.

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

fn main() {
    let handle = thread::spawn(|| {
        for _index in 1..10 {
            println!("in the spawned thread");
            thread::sleep(Duration::from_millis(1));
        }
    });

    for _index in 1..5 {
        println!("in the main thread");
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

The return value of the spawned thread is stored in a handle variable and then we call a join method on it so that our spawned thread executes completely even when our main thread is completed. The output of the above code is given below.

in the main thread
in the spawned thread
in the main thread
in the spawned thread
in the main thread
in the spawned thread
in the main thread
in the spawned thread
in the spawned thread
in the spawned thread
in the spawned thread
in the spawned thread
in the spawned thread

Now you can see after the main thread was over, the spawned thread was executed fully. This allows us to implement concurrency in Rust.

So this was an introduction to threads in Rust. Stay tuned for upcoming blogs on Concurrency in Rust.


If you want to read more content like this?  Subscribe to Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe to Rust Times Newsletter: https://bit.ly/2Vdlld7.


concurrency threads

1 thought on “Concurrency in Rust is indeed fearless4 min read

Comments are closed.