ADVERTISEMENT
ADVERTISEMENT

Rust program to send a message between threads

Rust | Thread Example: Write a program to send a message between threads.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

In this program, we will send a message from thread to main thread using send() and receive() function and print the received message.

Program/Source Code:

The source code to send a message between threads is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to send message 
// between threads

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

fn main() {
    let (tx, rx) = mpsc::channel();
    
    thread::spawn(move || {
        let msg1 = "hello";
        
        // Send message to main thread.
        tx.send(msg1).unwrap();
    });
    
    // Receive message from thread.
    let msg2 = rx.recv().unwrap();
    println!("Message received: {}", msg2);
}

Output:

$ rustc main.rs

$ ./main
Message received: hello

Explanation:

Here, we send a message by specifying a string variable in send() function from worker thread to main thread. In the main thread, we used the recv() function to receive a message and printed the received message.

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.