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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer