这是代码:
use std::thread;
use std::sync::mpsc;
fn main() {
//spawn threads
let (tx, rx) = mpsc::channel();
for mut i in 0 .. 10 {
let txc = tx.clone(); //clone from the main sender
thread::spawn( move || {
i += 20;
println!("Sending: {}", i);
txc.send(i).unwrap_or_else(|e| {
eprintln!("{}", e);
});
});
}
for received in rx {
println!("Received: {}", received);
}
}
Run Code Online (Sandbox Code Playgroud)
代码成功运行,但它挂起并且进程最终永远不会退出。
我认为这可能与关闭通道结束有关,我尝试顺便拜访一下tx.drop()
,rx.drop()
但编译器给出了错误。
我在这里做错了什么?
tx
在您的主线程中,直到函数结束才被删除main
,并且rx
直到所有发件人都被删除后才会关闭。
drop(tx)
要解决此问题,您可以在启动所有线程后手动将其删除:
use std::thread;
use std::sync::mpsc;
fn main() {
//spawn threads
let (tx, rx) = mpsc::channel();
for mut i in 0 .. 10 {
let txc = tx.clone(); //clone from the main sender
thread::spawn( move || {
i += 20;
println!("Sending: {}", i);
txc.send(i).unwrap_or_else(|e| {
eprintln!("{}", e);
});
});
}
// drop tx manually, to ensure that only senders in spawned threads are still in use
drop(tx);
for received in rx {
println!("Received: {}", received);
}
}
Run Code Online (Sandbox Code Playgroud)