这是代码:
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);
}
}
代码成功运行,但它挂起并且进程最终永远不会退出。
我认为这可能与关闭频道结束有关,我尝试顺便过去tx.drop()
and 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)