We can facilitate communication between the main thread and the spawned thread.
In this example the spawned thread is sending a message to the main thread.
The move keyword tells Rust that the variables declared before spawning that are also used in the spawned code need to be moved. (tx in this case)
We can use recv, which is blocking the main thread, to wait for a message from the spawned thread.
In that case we will have to know how many messages to expect and if we are still waiting for a message while the spawned thread exits then we either get stuck or get panic!.
Using the second loop is a better solution.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("Hello");
tx.send(val).unwrap();
for i in 1..=10 {
thread::sleep(Duration::from_millis(1));
tx.send(i.to_string()).unwrap();
}
// thread::sleep(Duration::from_millis(1));
println!("Spawned thread ends");
});
let received = rx.recv().unwrap();
println!("Received: {}", received);
// complex way for reveiving
for _j in 1..=5 {
let received = rx.recv().unwrap();
println!("Received: {}", received);
}
println!();
// simple code for receiving
for received in rx {
println!("Received: {}", received);
}
println!();
println!("Main thread ends");
}