Q:

Rust program to send multiple messages between threads

belongs to collection: Rust Threads Programs

0

In this program, we will send and receive multiple messages between threads 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 multiple messages between threads is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to send multiple messages 
// between threads

use std::thread;
use std::time::Duration;
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    
    thread::spawn(move || {
        tx.send("Message 1").unwrap();
        tx.send("Message 2").unwrap();
        tx.send("Message 3").unwrap();
        tx.send("Message 4").unwrap();
        
        thread::sleep(Duration::from_millis(500));
    });
    
    //Receive messages from thread.
    for msg in rx {
        println!("Message: {}", msg);
        thread::sleep(Duration::from_millis(500));
    }
}

Output:

$ rustc main.rs

$ ./main
Message: Message 1
Message: Message 2
Message: Message 3
Message: Message 4

Explanation:

Here, we created a thread and send messages to the main thread using send() function and printed the received message in the main thread.

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

total answers (1)

Rust program to send multiple messages between thr... >>
<< Rust program to pass a channel to the function...