Q:

Rust program to pass a channel to the function

belongs to collection: Rust Threads Programs

0

In this program, we will pass a channel to the function and send a message to the main thread 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 pass a channel to the function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to pass a channel 
// to the function

use std::thread;
use std::sync::mpsc;

fn fun(chnl: mpsc::Sender<i32>) {
    // Send a integer value
    chnl.send(786).unwrap();
}

fn main() {
    let (tx, rx) = mpsc::channel();
    
    thread::spawn(move || {
        // Pass channel as a parameter.
        fun(tx);
    });
    
    // Receive message from thread.
    let val = rx.recv().unwrap();
    println!("Message received: {}", val);
}

Output:

$ rustc main.rs

$ ./main
Message received: 786

Explanation:

Here, we created two functions fun() and main(). The fun() function accepts the channel as a parameter and sends the message to the main thread. And, we created a thread and called the fun() function to send a message. Then we received the message using the recv() function and printed the received message.

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 send a message between threads...