w3resource

Rust Multi-Sender, Single-Receiver Communication

Rust Error Propagation: Exercise-3 with Solution

Write a Rust program that creates multiple sender threads and a single receiver thread. Each sender thread sends a message through the channel, and the receiver thread prints the messages.

Sample Solution:

Rust Code:

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

const NUM_SENDERS: usize = 3;
const NUM_MESSAGES_PER_SENDER: usize = 5;

fn main() {
    // Create a channel for communication between sender and receiver threads
    let (sender, receiver) = mpsc::channel();

    // Spawn sender threads
    for i in 0..NUM_SENDERS {
        let sender_clone = sender.clone(); // Clone sender for each thread
        thread::spawn(move || {
            // Send messages from each sender thread
            for j in 0..NUM_MESSAGES_PER_SENDER {
                let message = format!("Sender {} Message {}", i + 1, j + 1);
                sender_clone.send(message).expect("Failed to send message");
            }
        });
    }

    // Spawn receiver thread
    thread::spawn(move || {
        // Receive and print messages from all sender threads
        for received in receiver {
            println!("Received: {}", received);
        }
    });

    // Wait for all threads to finish
    thread::sleep(std::time::Duration::from_secs(1));
}

Output:

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

Explanation:

In the exercise above,

  • Imports and Constants:
    • Import necessary modules from the standard library, including std::sync::mpsc for creating channels and std::thread for handling threads.
    • Constants 'NUM_SENDERS' and 'NUM_MESSAGES_PER_SENDER' define the number of sender threads to spawn and the number of messages each sender will send, respectively.
  • Main Function:
    • Inside the "main()" function, a channel is created using mpsc::channel(). This channel will be used for communication between sender and receiver threads.
  • Sender Threads:
    • A loop spawns multiple sender threads. For each sender thread:
      • A clone of the sender endpoint is created using "sender.clone()". This ensures that each sender thread has its own sender.
      • A new thread is spawned, and within its closure, it sends a fixed number of messages through the channel using 'sender_clone.send(message)'.
  • Receiver Thread:
    • Another thread is spawned to act as a receiver. Inside its closure, it continuously receives messages from the channel using a loop and prints each received message to the console.
  • Thread Synchronization:
    • To ensure that the main thread does not exit before all other threads complete their execution, a brief pause is introduced using thread::sleep(std::time::Duration::from_secs(1)).
  • Execution Flow:
    • The sender threads run concurrently, sending messages through the channel.
    • The receiver thread also runs concurrently, continuously receiving and printing messages from the channel.
    • Once all threads complete their tasks, the program exits.

Rust Code Editor:

Previous: Rust Multi-Message Channel Communication.
Next: Rust Producer-Consumer Pattern with Channels.

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://www.w3resource.com/rust/channels/rust-message-passing-exercise-3.php