如何在Rust中实现单一生产者,多个消费者(SPMC)渠道?

时间:2018-06-17 03:03:58

标签: rust

标准库只有多个生产者,单一消费者(MPSC)渠道。

也就是说,如果有10个消费者,每个消费者如何收到单个生产者发送的消息?

1 个答案:

答案 0 :(得分:2)

查看bus@CodesInChaos mentioned包。一个工作的例子:

extern crate bus;

use std::thread;

fn main() {
    let mut bus = bus::Bus::new(10);
    let mut receiver1 = bus.add_rx();
    let mut receiver2 = bus.add_rx();
    let mut receiver3 = bus.add_rx();

    let a = thread::spawn(move || {
        println!("receiver1 - {}", receiver1.recv().expect("1"));
    });
    let b = thread::spawn(move || {
        println!("receiver2 - {}", receiver2.recv().expect("2"));
    });
    let c = thread::spawn(move || {
        println!("receiver3 - {}", receiver3.recv().expect("3"));
    });

    bus.broadcast(42);
    a.join().expect("a");
    b.join().expect("b");
    c.join().expect("c");
}