Home »
Rust »
Rust Programs
Rust program to demonstrate the Sender::clone() function
Rust | Thread Example: Write a program to demonstrate the Sender::clone() function.
Last Updated : November 06, 2021
Problem Statement
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);
}
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.
Rust Threads Programs »
Advertisement
Advertisement