w3resource

Rust Multi-Message Channel Communication

Rust Error Propagation: Exercise-2 with Solution

Write a Rust program that extends the previous program to send multiple messages through the channel and print them in the receiving thread.

Sample Solution:

Rust Code:

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

const NUM_MESSAGES: usize = 5;

fn main() {
    // Create a channel for sending and receiving messages
    let (sender, receiver) = mpsc::channel();

    // Spawn a sender thread to send messages
    let sender_thread = thread::spawn(move || {
        // Send multiple messages through the channel
        for i in 0..NUM_MESSAGES {
            let message = format!("Message {}", i + 1);
            sender.send(message).expect("Failed to send message");
        }
    });

    // Spawn a receiver thread to receive and print messages
    let receiver_thread = thread::spawn(move || {
        // Receive and print multiple messages from the channel
        for _ in 0..NUM_MESSAGES {
            let received_message = receiver.recv().expect("Failed to receive message");
            println!("Received: {}", received_message);
        }
    });

    // Wait for the sender thread to finish
    sender_thread.join().expect("Sender thread panicked");

    // Wait for the receiver thread to finish
    receiver_thread.join().expect("Receiver thread panicked");
}

Output:

Received: Message 1
Received: Message 2
Received: Message 3
Received: Message 4
Received: Message 5

Explanation:

In the exercise above,

  • Channel Creation:
    • It creates a channel using "mpsc::channel()" from the "std::sync" module. This channel allows one-way communication between threads.
  • Sender Thread:
    • A new thread is spawned using "thread::spawn()". This thread sends multiple messages through the channel using a loop.
    • Each message is a string formatted as "Message {i+1}".
  • Receiver Thread:
    • Another thread is spawned to receive and print messages from the channel.
    • It also uses a loop to receive a fixed number of messages (defined by 'NUM_MESSAGES' constant).
    • Each received message is printed to the console.
  • Joining Threads:
    • After spawning the sender and receiver threads, the main thread waits for both threads to complete their execution using "join()" method.
    • This ensures that the program doesn't exit before both threads finish processing.
  • Execution:
    • When executed, the program will first spawn the sender and receiver threads concurrently.
    • The sender thread sends messages through the channel, and the receiver thread receives and prints them.
    • Finally, the main thread waits for both threads to finish before exiting.

Rust Code Editor:

Previous: Rust Thread Communication with Channels.
Next: Rust Multi-Sender, Single-Receiver Communication.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/channels/rust-message-passing-exercise-2.php