How to Use the Rust MPSC

Muhammad Adil Feb 02, 2024
  1. Types of Channels
  2. Steps to Use the Rust MPSC
How to Use the Rust MPSC

Rust has many features that make it an appealing choice for programmers. One is the ability to send messages of different types over the same channel.

This feature allows Rust programmers to avoid data races and control their program’s memory usage more. This Rust channel tutorial will focus on sending different types using the same channel.

The MPSC (multiple producers, single consumers) is an excellent way to send messages in a Rust program. The MPSC is a queue that can be used for both sending and receiving messages.

Sending messages in Rust can be done through channels available in the std::sync module. Channels provide an interface for sending and receiving data between threads or processes without locking or explicit synchronization.

Types of Channels

There are two types of channels available:

An Indefinitely Buffered, Asynchronous Channel

All sends will be asynchronous; hence, the channel function will return a (Sender, Receiver) tuple (they never block). The channel has an endless buffer in theory.

A Bounded, Synchronous Channel

The sync channel method returns a (SyncSender, Receiver) tuple with a pre-allocated buffer size for waiting messages. All transmissions will be synchronous and blocked until there is enough buffer space.

It’s worth noting that a bound of 0 allows the channel to become a rendezvous channel, in which each sender atomically sends a message to a receiver.

Steps to Use the Rust MPSC

To use channels in Rust, you must import the MPSC crate. The steps are as follows:

  • Import the crate by adding this line at the top of your file:
    use mpsc::{Sender, Receiver};
    
  • Create a new Sender and Receiver by adding this line after importing:
    let (tx, rx) = mpsc::channel();
    
  • Lastly, send messages on tx.

Let’s discuss an example.

use std::sync::mpsc::{self, Receiver, Sender};
enum Furniture {
    Bed(i32),
    Table(i32)
}
fn main() {
    let (tx, rx): (Sender<Furniture>, Receiver<Furniture>) = mpsc::channel();
    tx.send(Furniture::Table(2)).unwrap();
    tx.send(Furniture::Bed(4)).unwrap();
    for _ in 0..2 {
        match rx.recv().unwrap() {
            Furniture::Bed(a) => println!("Got {} Beds", a),
            Furniture::Table(b) => println!("Got {} Tables", b),
        }
    }
}

Output:

Got 2 Tables
Got 4 Beds

Click here to check the demonstration of the code mentioned above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook