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.
    // Receive message from thread.
    let msg2 = rx.recv().unwrap();
    println!("Message received: {}", msg2);


$ rustc

$ ./main
Message received: hello


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 All rights reserved.