Hello, I'm building something that has a feature like Pub/Sub similar to the one that in Redis, where some clients connect and subscribe to some topic/channel and other clients can publish data to that channel.
I thought at first that would be easier by using channels where every client handle a clone of tx and rx of that channel so the client can recv and send data over this channel.
I made a simple program (without any connection to the outworld) to test this idea.
//# crossbeam = "0.7.2"
use crossbeam::channel;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = channel::bounded(2);
let mut threads = Vec::new();
for i in 1..6 {
let rx = rx.clone();
let handle = thread::spawn(move || {
println!("thread #{} started !", i);
for item in rx.recv() {
println!("thread #{} got item: {}", i, item);
}
});
threads.push(handle);
}
thread::sleep(Duration::from_millis(500));
// send simple data
tx.send(true).unwrap();
for thread in threads {
let _ = thread.join();
}
}
and I started to run this program multiple times
$ cargo play bus.rs
Output #1:
thread #2 started !
thread #1 started !
thread #3 started !
thread #5 started !
thread #4 started !
thread #1 got item: true
Output #2:
thread #1 started !
thread #2 started !
thread #3 started !
thread #5 started !
thread #4 started !
thread #2 got item: true
Output #3:
thread #3 started !
thread #4 started !
thread #2 started !
thread #5 started !
thread #1 started !
thread #3 got item: true
so what I concluded from that simple test is that crossbeam channels will send the data at most once to one subscriber randomly! ( I'm not sure of that ).
so is there any way to send the item once from the tx and it would send as many clones of it to all the rx s?
Small Notes:
- I'm using
cargo playa small and nice project for running your code easily without setting up a cargo project (think a local version of play.rust-lang.org)- I'm aware of the
buscrate which doses just like that, but I'm looking for a using crossbeam.