Hello I'm trying to get multiple reciever using Arc<Mutex<Receiver>>. But one thread blocks everything. I don't know why. Can you explain and solve the problem?
use std::sync::mpsc::{self, Sender, Receiver};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx): (Sender<String>, Receiver<String>) = mpsc::channel();
let rx = Arc::new(Mutex::new(rx));
let mut join_handles = vec![];
for id in 0..2 {
let rx = rx.clone();
let join_handle = thread::spawn(move || loop {
match rx.lock().unwrap().recv() {
Ok(msg) => {
println!("Thread {} got a msg: {}", id, msg);
thread::sleep(Duration::from_millis(500));
}
Err(e) => {
println!("Thread {} got a error: {}", id, e);
break;
}
}
});
join_handles.push(join_handle);
}
for i in 0..5 {
tx.send(format!("msg#{}", i)).unwrap();
}
drop(tx);
for join_handle in join_handles {
join_handle.join().unwrap();
}
}