compiler/pitfalls/main-with-channel-blocked #949
Replies: 6 comments
-
挺坑的 多谢!~ |
Beta Was this translation helpful? Give feedback.
-
”其实,上面的描述有问题,主线程并不是卡死,而是for循环并没有结束,至于for循环不结束的原因是消息通道没有被关闭。 回忆一下 Rust 消息通道关闭的两个条件:所有发送者全部被drop或接收者被drop,由于for循环还在使用接收者,因为后者条件无法被满足,那么只能发送者全部被drop,才能让例子中的消息通道关闭。“ 这两句话不需要,其实是一个send没有被drop,文章下面写了,而不是for循环没完。 |
Beta Was this translation helpful? Give feedback.
-
可以尝试使用某个flag毒害消费者,让消费者自行退出 |
Beta Was this translation helpful? Give feedback.
-
用try_iter()也可以 use std::sync::mpsc;
fn main() {
use std::thread;
let (send, recv) = mpsc::channel();
let num_threads = 3;
for i in 0..num_threads {
let thread_send = send.clone();
thread::spawn(move || {
thread_send.send(i).unwrap();
println!("thread {:?} finished", i);
});
}
recv.try_iter().for_each(|msg| println!("Got: {}", msg));
println!("finished iterating");
} 区别是不能保证所有thread已经发送完 |
Beta Was this translation helpful? Give feedback.
-
估计还是官方教材的例子不够全面引起的。 |
Beta Was this translation helpful? Give feedback.
-
compiler/pitfalls/main-with-channel-blocked
https://course.rs/compiler/pitfalls/main-with-channel-blocked.html
Beta Was this translation helpful? Give feedback.
All reactions