#channel #csp #select

channel-drain

使用简单语法清空通道

1 个不稳定版本

0.1.0 2022年11月14日

并发 中排名 778

Zlib 许可证

8KB
89

channel-drain

清空(跨beam)通道。

霍尔是对的 - 我们应该优先使用通道而不是共享内存来在线程之间通信。在 Rust 中,一个线程消费单个通道是非常简单的

fn my_thread(rx: Receiver<i32>) {
    while let Ok(num) = rx.recv() {
        // Cool stuff
    }
}

太棒了!几乎不需要代码,它

  • 为你处理同步,当输入就绪时进行工作,当它们不就绪时睡眠。

  • 当没有输入时自动关闭自己。(我们可以构建整个 DAG,关闭原始生产者,并观察所有消费者优雅地关闭自己。)

但在更复杂的系统中,我们经常想要从 多个 通道接收。Crossbeam(以及一些其他的通道库)为此提供了一个很好的 Select 机制,但你需要写很多样板代码来删除关闭时正在轮询的集合中的通道。

不再需要了

fn smoke_test() {
    let (tx1, rx1) = bounded(10);
    let (tx2, rx2) = bounded(10);

    tx1.send("For a successful technology").unwrap();
    tx1.send("reality must take precedence over public relations").unwrap();
    tx1.send("for nature cannot be fooled").unwrap();
    tx2.send(42).unwrap();
    tx2.send(22).unwrap();
    tx2.send(99).unwrap();

    drop(tx1);
    drop(tx2);

    drain!{
        rx1(wisdom) => { println!("Feynman Says: \"{}\"", wisdom) },
        rx2(num) => println!("Some num: {}", num)
    };
}

它提供了

Some num: 42
Some num: 22
Feynman Says: "For a successful technology"
Some num: 99
Feynman Says: "reality must take precedence over public relations"
Feynman Says: "for nature cannot be fooled"

(Crossbeam 随机选择一个就绪通道以实现公平性。)

依赖关系

~2MB
~40K SLoC