ADVERTISEMENT
ADVERTISEMENT

Rust program to pass a channel to the function

Rust | Thread Example: Write a program to pass a channel to the function.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

In this program, we will pass a channel to the function and send a message to the main thread and print the received message.

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.

Rust Threads Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.