The following code hangs in iterator: (playground)
#![allow(unused)]
fn main() {
use std::sync::mpsc::channel;
use std::thread;
let (send, recv) = channel();
let num_threads = 3;
for i in 0..num_threads {
let thread_send = send.clone();
thread::spawn(move || {
loop { // exit condition does not matter, breaking right after the 1st iteration
&thread_send.send(i).unwrap(); // have to borrow in the loop
break;
}
println!("thread {:?} finished", i);
});
}
// drop `send` needed here (as it's cloned by all producers)?
for x in recv { // hanging
println!("Got: {}", x);
}
println!("finished iterating");
}
In the output we can clearly see the threads exited (so thread-local cloned senders are dropped):
thread 0 finished
Got: 0
Got: 1
Got: 2
thread 1 finished
thread 2 finished
finished iterating is never printed and the process is interrupted in playground (hangs forever locally).
What's the reason?
PS. Loop in the threads is required (it's a simplified example of the code that is actually used) to show the real use case.