Q:

Rust program to send a message between threads

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now