挂在 Rust 中的通道接收器迭代器中?

4ntoine

以下代码挂在迭代器中:(游乐场

#![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");
}

在输出中,我们可以清楚地看到退出的线程(因此线程本地克隆的发件人被删除):

thread 0 finished
Got: 0
Got: 1
Got: 2
thread 1 finished
thread 2 finished

finished iterating 永远不会打印并且该过程在操场上中断(在本地永远挂起)。

原因是什么?

附注。需要在线程中循环(这是实际使用的代码的简化示例)以显示真实用例。

HHK

您需要send在评论指示的位置放下,因为只有在最后一个发件人被放下时才会关闭频道。主线程的发送只会在它超出函数末尾的范围时被删除。

您可以拨打drop(send)您开始我们收到循环之前为Stargateur在评论(明确指出或重构代码,以便主线程的发送去的范围之操场)。这是更可取的,因为读者可以立即清楚在哪里send删除该drop(send)语句,而该语句很容易被遗漏。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章