Golang / GoLang Concurrency Mastery Interview Questions
Implement a simple publish-subscribe broker using Go channels.
A pub-sub system decouples publishers from subscribers. The idiomatic Go implementation uses a broker goroutine that owns the subscriber registry and distributes messages — a single goroutine owning a map eliminates all locking.
type Broker[T any] struct {
publish chan T
subscribe chan chan<- T
cancel chan chan<- T
quit chan struct{}
}
func NewBroker[T any]() *Broker[T] {
b := &Broker[T]{
publish: make(chan T, 64),
subscribe: make(chan chan<- T),
cancel: make(chan chan<- T),
quit: make(chan struct{}),
}
go b.run()
return b
}
func (b *Broker[T]) run() {
subs := map[chan<- T]struct{}{}
for {
select {
case <-b.quit:
for sub := range subs { close(sub) }
return
case sub := <-b.subscribe:
subs[sub] = struct{}{}
case sub := <-b.cancel:
delete(subs, sub); close(sub)
case msg := <-b.publish:
for sub := range subs {
select {
case sub <- msg: // non-blocking: slow subscribers may miss
default:
}
}
}
}
}
func (b *Broker[T]) Publish(v T) { b.publish <- v }
func (b *Broker[T]) Subscribe() <-chan T {
ch := make(chan T, 16)
b.subscribe <- ch
return ch
}
func (b *Broker[T]) Stop() { close(b.quit) }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
