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


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


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.

Follow us on Facebook and Twitter for latest update.