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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.