ADVERTISEMENT
ADVERTISEMENT

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

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


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.