Logo

Developer learning path

Rust

Message Passing in Rust

Message Passing

26

#description

In Rust, message passing is a mechanism where one thread or process sends a message to another thread or process, which receives and processes it. This is achieved using channels, which are Rust's implementation of a popular concurrent programming construct.

A channel is essentially a communication pipe that allows two endpoints to send and receive messages. Channels are unidirectional, meaning that one endpoint sends messages and the other receives them. The sending endpoint can only send messages, and the receiving endpoint can only receive them.

In Rust, we create a channel by calling the std::sync::mpsc::channel function, which returns a Sender and a Receiver. The Sender is used to send messages to the channel while the Receiver is used to receive messages.

Here's an example of using message passing to create a simple chat application in Rust:

                    
use std::sync::mpsc::{Sender, Receiver};
use std::thread;

fn main() {
    // Create a channel
    let (tx, rx): (Sender<String>, Receiver<String>) = mpsc::channel();

    // Spawn a new thread to handle incoming messages
    thread::spawn(move || {
        while let Ok(msg) = rx.recv() {
            println!("Received message: {}", msg);
        }
    });

    // Send a message
    tx.send(String::from("Hello, World!")).unwrap();
}
                  

In this example, we create a channel using mpsc::channel, and spawn a new thread that listens for incoming messages using rx.recv(). We then use tx.send() to send a message to the other thread.

Overall, message passing is a powerful tool for building concurrent applications in Rust. By using channels, developers can create highly efficient and scalable systems with minimal overhead.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.