Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement single producer, multiple consumer (SPMC) channels in Rust? [closed]

Tags:

rust

The standard library only has multiple producer, single consumer (MPSC) channels.

That is, if there are 10 consumers, how can every consumer receive a message sent by a single producer?

like image 344
Greg Avatar asked Jun 17 '18 03:06

Greg


1 Answers

Check out the bus crate that @CodesInChaos mentioned. A working example:

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");
}
like image 84
tsatiz Avatar answered Nov 13 '22 14:11

tsatiz