4nt*_*ine 4 concurrency multithreading channel rust
以下代码挂在迭代器中:(游乐场)
#![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");
}
Run Code Online (Sandbox Code Playgroud)
在输出中,我们可以清楚地看到线程已退出(因此线程本地克隆的发送者被删除):
thread 0 finished
Got: 0
Got: 1
Got: 2
thread 1 finished
thread 2 finished
Run Code Online (Sandbox Code Playgroud)
finished iterating永远不会被打印,并且该过程在操场上被中断(在本地永远挂起)。
什么原因?
附言。需要在线程中循环(这是实际使用的代码的简化示例)来显示真实的用例。