关闭频道,就像Go一样

joc*_*ull 8 channel rust

Rust是否有办法"关闭"一个频道,类似于Go中提供的频道?

我们的想法是迭代通道(连续接收),直到通道指示它不再产生任何值.

use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;

fn main() {
    let data = Arc::new(Mutex::new(0u32));
    let (tx, rx) = mpsc::channel::<u32>();
    {
        let (data, tx) = (data.clone(), tx.clone());
        thread::spawn(move || {
            for _ in 0..10 {
                let mut data = data.lock().unwrap();
                *data += 1;
                tx.send(*data).unwrap();
            }
            // *** How could I close the channel here, to signal the work is done?
        });
    }

    // *** How can I detect a closed channel here? Pattern matching?
    for _ in 0..10 {
        let x = rx.recv().unwrap();
        println!("{}", x);
    }
}
Run Code Online (Sandbox Code Playgroud)

blu*_*uss 17

当所有发件人都已丢弃时,该频道将关闭.在您的代码中,您克隆并为每个线程分别提供一个,这些线程在线程结束时应该丢弃.最后一个发送者在主线程中,你应该在产生所有线程后立即删除它:drop(tx).

最后,获得最简单的方法是这样的,以后drop(tx).

for elt in rx {
    /* */
}
Run Code Online (Sandbox Code Playgroud)

当通道关闭时,此循环结束.

  • 在这种情况下绝对是浪费——只是一个例子。根据线程内的资源,它可能会有所不同? (2认同)