belongs to collection: Rust Threads Programs
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.
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer