Message Passing in Rust Threads is very helpful

Reading Time: 3 minutes

Rust has been the most loved programming language for the last five years in a row. It is a low-level statically-typed multi-paradigm programming language that’s focused on safety and performance. Rust has facilities for message passing through an mpsc channel which allows various threads to communicate.

Rust solves problems that C/C++ has been struggling with for a long time, such as memory errors and building concurrent programs. Due to the borrow checker, Rust can prevent data races at compile-time. Data races occur when two threads access the same memory at the same time, and they can lead to unpredictable behaviour. Thankfully, preventing undefined behaviour is all that Rust is about. 

In our previous blogs, I have shown you how we can create a thread in Rust and achieve multithreading. Now in this blog, I will tell you how can you make a Rust thread communicate with another thread via a channel.

File:Rust programming language black logo.svg - Wikimedia Commons

A channel for message passing

We will achieve the communication between the threads using message passing. We will use a channel to pass messages between threads in Rust.

A channel is like a transmission medium that allows communication. A channel in programming has two halves: a transmitter and a receiver

The transmitter end sends a message and the receiver end is continuously looking for any message to come from the transmission end. As soon as the receiver receives a message it provides the message to the thread that is using the receiver end.

MPSC Channel

MPSC stands for Multiple Producer Single Consumer. It is a channel that allows multiple transmission ends to send the data but only one receiver end to receive it.

In short, the way Rust’s standard library implements channels means a channel can have multiple sending ends that produce values but only one receiving end that consumes those values.

We create a new channel using the mpsc::channel function. The sample code to create an mpsc channel is given below.

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
}

The above code uses the mpsc::channel method to return Sender and Receiver objects that are stored in tx and rx variables.

Now we can use the tx and rx variables to send and receive messages across different threads.

Sending data in mpsc channel

Now we will see how we can send messages using the mpsc channel from one thread. The following code shows how the send method of the Sender object is used to send the data.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });
}

As you can see, firstly we have created an mpsc channel using the mpsc::channel method. Then we have created a thread using the spawn method. In this thread, we have used the send method of the tx object to send the string ‘hi’ to the mpsc channel.

Receiving the message from mpsc channel

Till now we have sent the data from the spawned thread using the send method of the transmitter object. Now we will see how we can receive the message from the channel.

The code below shows how we can receive the string that we sent from the spawned thread in our main thread.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

The above code uses the recv() method of the Receiver object to extract messages from the communication channel. The recv() method returns the Result type value, so we need to unwrap it to get the actual message.

The output which we get is as follows-

Got: hi

This was all about message-passing through mpsc channel. Stay tuned for more blogs.


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.


message passing mpsc

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading