Close Broadcast Channels Exactly Once
Guard a broadcast close with sync.Once so the second call is a no-op instead of a panic, and every subscriber drains its channel cleanly.
Code
package main
import (
"fmt"
"sync"
)
func main() {
inboxes := make([]chan string, 3)
for i := range inboxes {
inboxes[i] = make(chan string, 4) // 缓冲足够,发送方永不阻塞
}
// close 只能调用一次:重复 close 未关闭/已关闭之外的语义都是 panic
// sync.Once 保证多个触发点(超时/信号/错误)也只执行第一笔
var closeOnce sync.Once
closeAll := func() {
closeOnce.Do(func() {
for _, ch := range inboxes {
close(ch)
}
})
}
var wg sync.WaitGroup
received := make([][]string, len(inboxes))
for i, ch := range inboxes {
wg.Add(1)
go func(i int, ch chan string) {
defer wg.Done()
for msg := range ch { // close 后 range 自然结束
received[i] = append(received[i], msg)
}
}(i, ch)
}
for _, msg := range []string{"deploy", "scale", "rollback"} {
for _, ch := range inboxes {
ch <- msg
}
}
closeAll()
closeAll() // 第二次被 sync.Once 挡下:直接 close 会 panic
wg.Wait()
for i, got := range received {
fmt.Printf("subscriber %d: %v\n", i, got)
}
}Why the guard exists
Closing a channel twice panics, and a broadcast hub usually has several trigger points — a timeout, a signal, an error path — any of which may fire. sync.Once collapses them: closeAll runs its inner loop of close(ch) calls exactly once, and the second closeAll() call in main is a no-op instead of a panic.
How the demo wires it
Three buffered inboxes (each make(chan string, 4)) are served by three subscriber goroutines. Each subscriber ranges over its channel, so the close ends its loop naturally, and a sync.WaitGroup waits for all of them. The publisher then pushes the messages deploy, scale, and rollback into every inbox before calling closeAll twice.
Reading the output
Each subscriber prints its three messages in send order, so the run shows subscriber 0: [deploy scale rollback] through subscriber 2: [deploy scale rollback] — proof that the guarded close drained every inbox exactly once.
Interactive Tools for This Topic
FAQ
- What happens on the second closeAll() call?
- Nothing. sync.Once has already run, so Do skips the function body and the second call returns immediately — this is exactly the double-close panic being prevented.
- Why are the inboxes buffered?
- Each inbox is created with a capacity of 4, so the publisher can push all three messages without blocking even before subscribers are scheduled; the close then drains the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.