w3resource

Rust Thread Communication with Channels

Rust Error Propagation: Exercise-1 with Solution

Write a Rust program that creates two threads and uses a channel to send a message from one thread to another.

Sample Solution:

Rust Code:

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

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

    // Spawn a thread that sends a message
    let sender_thread = thread::spawn(move || {
        let message = "Hello from sender thread!";
        sender.send(message).expect("Failed to send message");
        println!("Sender thread sent a message: {}", message);
    });

    // Spawn another thread that receives the message
    let receiver_thread = thread::spawn(move || {
        let received_message = receiver.recv().expect("Failed to receive message");
        println!("Receiver thread received a message: {}", received_message);
    });

    // Wait for both threads to finish
    sender_thread.join().expect("Failed to join sender thread");
    receiver_thread.join().expect("Failed to join receiver thread");
}

Output:

Sender thread sent a message: Hello from sender thread!
Receiver thread received a message: Hello from sender thread!

Explanation:

In the exercise above,

  • Channel Creation:
    • mpsc::channel(): Creates a channel for sending and receiving messages between threads. It returns a tuple containing a sender and receiver.
  • Sender Thread:
    • thread::spawn(move || { ... }): Spawns a new thread to execute the provided closure concurrently.
    • Inside the closure:
      • A message "Hello from sender thread!" is created.
      • sender.send(message): Sends the message through the channel's sender. If successful, the message is sent; otherwise, it panics with the specified error message.
  • Receiver Thread:
    • thread::spawn(move || { ... }): Spawns another thread to execute the provided closure concurrently.
    • Inside the closure:
      • receiver.recv(): Receives a message from the channel's receiver. If successful, it returns the received message; otherwise, it panics with the specified error message.
  • Joining Threads:
    • sender_thread.join(): Waits for the sender thread to finish executing. If successful, it returns a 'Result' indicating whether the thread panicked or completed successfully.
    • receiver_thread.join(): Waits for the receiver thread to finish executing. If successful, it returns a 'Result' indicating whether the thread panicked or completed successfully.
  • Execution:
    • The program creates two threads: one to send a message and another to receive it.
    • The sender thread sends a message through the channel.
    • The receiver thread receives the message from the channel and prints it.
    • Both threads are joined to ensure execution before the program exits.

Rust Code Editor:

Previous: Rust Error Propagation Exercises.
Next: Rust Multi-Message Channel Communication.

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.