You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[utils/broadcast] Make Broadcaster.Close() idempotent and prevent post-close deadlocks #1179
While adding unit tests for utils/broadcast (broadcaster.go), two lifecycle concurrency bugs were identified and confirmed during review:
Calling Close() more than once panics: Broadcaster.Close() executes close(b.reg) directly without synchronization. Invoking Close() more than once (for example, an explicit shutdown followed by defer b.Close()) triggers a runtime panic (panic: close of closed channel).
Post-close Register(), Unregister(), and Submit() calls deadlock:
When Close() closes b.reg, the background b.run() goroutine exits via else { return }. Once b.run() terminates:
Register() (b.reg <- newch) and Unregister() (b.unreg <- newch) block indefinitely because both channels are unbuffered and have no active receiver.
Submit() (b.input <- m) blocks indefinitely once the buffered b.input channel (buflen) fills up because b.run() is no longer draining messages.
Proposed Fix
Add closeOnce sync.Once and done chan struct{} fields to broadcaster (initialized in NewBroadcaster).
Inside Close(), use b.closeOnce.Do(...) to close b.done and b.reg exactly once, making Close() idempotent.
Update Register(), Unregister(), and Submit() to select on <-b.done alongside their channel sends so post-close calls return immediately instead of blocking forever.
Add unit tests in utils/broadcast/broadcast_test.go covering idempotent Close() and non-blocking post-close Register, Unregister, and Submit under go test -race.
Activity