ADVERTISEMENT
ADVERTISEMENT

Rust program to send multiple messages between threads

Rust | Thread Example: Write a program to send multiple messages between threads.
Submitted by Nidhi, on November 06, 2021

Problem Solution:

In this program, we will send and receive multiple messages between threads and print the received message.

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.

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.