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

Rust | Thread Example: Write a program to demonstrate the Sender::clone() function.
Submitted by Nidhi, on November 06, 2021

Problem Solution:

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

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);


$ rustc

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


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.

Rust Threads Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.