pub struct Carousel { /* private fields */ }
Expand description
Carousel
represents a multi producer multi polling consumer data carousel. It enables
message passing from multiple producers to multiple consumers asynchronously.
It accepts a vector of bytes as a message/ event.
A mp2c Carousel
can be created for a list of consumers. However, each consumer
is expected to implement the Consumer
trait.
A multiplier thread is started which receives one end of an async channel.
Each message put
on the Carousel
is sent to this multiplier thread. The job
of the Multiplier
is to clone each incoming event/ message and send it to each
polling consumer.
For each consumer, a poller thread is started which receives one end of an async
channel. The transmitting end of the channel is with the Multiplier
thread. The
poller calls Consumer::consume
on it’s registered consumer.
An Carousel
can be cloned and the clone creates a clone of the Sender
from which it is
cloned. When Carousel::put
is called to send a message, it’ll be sent to the pollers in
the originating Carousel
.
§Example
use mp2c::asynch::{Carousel, Consumer};
struct TestConsumer1;
impl Consumer for TestConsumer1 {
fn consume(&mut self, data: Vec<u8>) {
let msg = String::from_utf8(data).unwrap();
// do something with msg
}
}
struct TestConsumer2;
impl Consumer for TestConsumer2 {
fn consume(&mut self, data: Vec<u8>) {
let msg = String::from_utf8(data).unwrap();
// do something with msg
}
}
let mut v: Vec<Box<dyn Consumer + Send + 'static>> = Vec::new();
v.push(Box::new(TestConsumer1));
v.push(Box::new(TestConsumer2));
let c = Carousel::new(v);
for _ in 1..10 {
let cloned_c = c.clone();
let t = std::thread::spawn(move || {
cloned_c.put(String::from("test").into_bytes());
});
t.join().unwrap();
}