Pub/Sub Broker (Rust)
Topics: RwLock, channels, threads, generics
Problem
Implement a generic Broker<T> that broadcasts published values to all active subscribers.
pub type Unsubscribe = Box<dyn Fn() + Send + Sync>;
pub struct Broker<T> { /* … */ }
impl<T: Clone + Send + 'static> Broker<T> {
pub fn new() -> Self;
pub fn subscribe(&self) -> (Receiver<T>, Unsubscribe);
pub fn publish(&self, v: T);
pub fn close(&self);
}
subscribe registers a subscriber and returns its receive channel plus an Unsubscribe handle;
calling the handle removes the subscriber and closes its channel (idempotent).
publish sends v to all current subscribers without blocking — a subscriber whose buffer
is full is skipped.
close closes every subscriber channel; later publish calls are no-ops.
subscribe, publish, unsubscribe, and close must be safe to call concurrently.
Key concepts
RwLock: take a read lock during publish (many publishers in parallel), a write lock for
subscribe/unsubscribe/close.
- Bounded subscriber channels:
sync_channel(16) gives each subscriber a buffer; try_send
makes the broadcast non-blocking and drops to a slow subscriber.
- Map of subscribers:
HashMap<usize, SyncSender<T>> keyed by a monotonic id; dropping a
stored sender closes that subscriber's channel.
- Closed flag: a lock-protected
bool prevents double-close and ignores post-close publishes.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.