w3resource

Implementing Synchronous Channels in Rust

Rust Error Propagation: Exercise-6 with Solution

Write a Rust program to implement the use of synchronous channels. Create a channel with synchronous communication and send messages between threads, ensuring that messages are received before continuing.

Sample Solution:

Rust Code:

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

const NUM_MESSAGES: usize = 5;

fn main() {
    // Create a synchronous channel for communication
    let (sender, receiver) = mpsc::sync_channel(NUM_MESSAGES);

    // Spawn a thread to send messages
    let sender_thread = thread::spawn(move || {
        for i in 0..NUM_MESSAGES {
            sender.send(i).unwrap(); // Send a message
            println!("Sent: {}", i);
        }
    });

    // Spawn a thread to receive messages
    let receiver_thread = thread::spawn(move || {
        for _ in 0..NUM_MESSAGES {
            let message = receiver.recv().unwrap(); // Receive a message
            println!("Received: {}", message);
        }
    });

    // Wait for sender and receiver threads to finish
    sender_thread.join().unwrap();
    receiver_thread.join().unwrap();
}

Output:

Sent: 0
Sent: 1
Sent: 2
Sent: 3
Sent: 4
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4

Explanation:

In the exercise above,

  • We create a synchronous channel using 'mpsc::sync_channel', specifying the buffer size as 'NUM_MESSAGES'.
  • Two threads are spawned: one for sending messages and one for receiving messages.
  • The sender thread iterates over a range and sends messages through the channel using 'sender.send(i)'.
  • The receiver thread iterates over the same range and receives messages using 'receiver.recv()'.
  • As the channel is synchronous, the sender blocks until the receiver is ready to receive the message, ensuring synchronization.
  • Both the sender and receiver threads are joined to the main thread to ensure they complete their tasks before the program exits.

Rust Code Editor:

Previous: Simulating a Message Passing Network in Rust.
Next: Implementing a Message Broadcast System in Rust.

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-6.php