- Sending messages from more than one spawned threads to the main thread.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx1, rx) = mpsc::channel();
let tx2 = tx1.clone();
println!("{:?}: start", thread::current().id());
thread::spawn(move || {
for i in 1..=5 {
thread::sleep(Duration::from_millis(1));
tx1.send(format!("{:?}: {}", thread::current().id(), i))
.unwrap();
}
println!("Spawned thread {:?} ends", thread::current().id());
});
thread::spawn(move || {
for i in 1..=5 {
thread::sleep(Duration::from_millis(1));
tx2.send(format!("{:?}: {}", thread::current().id(), i))
.unwrap();
}
println!("Spawned thread {:?} ends", thread::current().id());
});
for received in rx {
println!("Received: {received}");
}
println!("Main thread ends");
}
ThreadId(1): start
Received: ThreadId(2): 1
Received: ThreadId(3): 1
Received: ThreadId(2): 2
Received: ThreadId(3): 2
Received: ThreadId(2): 3
Received: ThreadId(3): 3
Received: ThreadId(2): 4
Received: ThreadId(3): 4
Spawned thread ThreadId(2) ends
Received: ThreadId(2): 5
Spawned thread ThreadId(3) ends
Received: ThreadId(3): 5
Main thread ends