Q:

Rust program to demonstrate the Sender::clone() function

0

In this program, we will send values from multiple threads by cloning our sender with the Sender::clone() function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate Sender::clone() function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to demonstrate the 
// Sender::clone() function.

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

fn main() {
    let (tx, rx) = mpsc::channel();
    
    // clone the sender
    let tx1 = mpsc::Sender::clone(&tx);
    
    thread::spawn(move || {
        tx.send("Message 1").unwrap();
    });
    
    thread::spawn(move || {
        tx1.send("Message 2").unwrap();
    });
    
    //Receive messages from thread.
    let mut msg:&str = rx.recv().unwrap();
    println!("Received Message: {}", msg);
    
    msg = rx.recv().unwrap();
    println!("Received Message: {}", msg);
}

Output:

$ rustc main.rs

$ ./main
Received Message: Message 2
Received Message: Message 1

Explanation:

Here, we created a channel to send messages between threads. Then we used Sender::clone() function to clone the sender to send values from multiple threads. After that, we created two threads and send messages to the main thread. In the main thread, we received messages and printed them.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now