Pub/Sub Broker
Source: Custom
Topics: sync.RWMutex, Channels, Goroutines, Generics
Problem
Implement a generic Broker[T] that broadcasts published values to all active subscribers.
Requirements:
Subscribe() (<-chan T, func()) — register a subscriber; return its receive channel and an unsubscribe function.
Publish(v T) — send v to all current subscribers; slow subscribers are skipped (non-blocking send).
Close() — close all subscriber channels; further Publish calls are no-ops.
- Handle concurrent
Subscribe, Publish, Unsubscribe, and Close safely.
Type:
type Broker[T any] struct { ... }
func NewBroker[T any]() *Broker[T]
func (b *Broker[T]) Subscribe() (<-chan T, func())
func (b *Broker[T]) Publish(v T)
func (b *Broker[T]) Close()
Key concepts
- sync.RWMutex:
RLock during Publish (many publishers OK), Lock during subscribe/unsubscribe/close.
- Buffered subscriber channels: give each subscriber a buffer so a slow reader doesn't block the publisher.
- Map of subscribers:
map[int]chan T keyed by a monotonic ID assigned at subscribe time.
- Closed flag: a mutex-protected bool prevents double-close and ignores post-close publishes.
Run
go test -v -race ./challenges/concurrency/pubsub/
Sign in to submit your solution.