use dcl_data_structures::ring_buffer::prelude::*;
use std::thread;
use std::time::{Duration, Instant};
struct PrintHandler;
impl EventHandler<i32> for PrintHandler {
fn handle_event(&self, event: &i32, sequence: u64, end_of_batch: bool) {
println!("Print handler received: {} at sequence {}", event, sequence);
if end_of_batch {
println!("Print handler batch ended at sequence {}", sequence);
}
}
}
struct MultiplyHandler;
impl EventHandlerMut<i32> for MultiplyHandler {
fn handle_event(&mut self, event: &mut i32, sequence: u64, _end_of_batch: bool) {
*event *= 2;
println!(
"Multiply handler: new value = {} at sequence {}",
event, sequence
);
}
}
struct StatsHandler {
count: usize,
sum: i32,
}
impl StatsHandler {
fn new() -> Self {
Self { count: 0, sum: 0 }
}
}
impl EventHandlerMut<i32> for StatsHandler {
fn handle_event(&mut self, event: &mut i32, sequence: u64, _end_of_batch: bool) {
self.count += 1;
self.sum += *event;
println!(
"Stats handler: count = {}, sum = {}, avg = {} at sequence {}",
self.count,
self.sum,
self.sum as f64 / self.count as f64,
sequence
);
}
}
fn main() {
println!("\nRunning single producer with multiple consumers example...");
let start_time = Instant::now();
let (executor, producer) = RustDisruptorBuilder::with_ring_buffer::<i32, 1024>(1024)
.with_blocking_wait()
.with_single_producer()
.with_barrier(|scope| {
scope.handle_events(PrintHandler);
})
.with_barrier(|scope| {
scope.handle_events_mut(MultiplyHandler);
})
.with_barrier(|scope| {
scope.handle_events_mut(StatsHandler::new());
})
.build();
let handle = executor.spawn();
for i in 0..5 {
producer.write(std::iter::once(i + 1), |slot, _, val| *slot = *val);
thread::sleep(Duration::from_millis(10)); }
drop(producer);
handle.join();
let duration = start_time.elapsed();
println!(
"Single producer multi-consumer example completed in {:?}",
duration
);
}