Home »
Rust »
Rust Programs
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 »