Broadcast values to multiple channels
b := broadcast.New[int](0).WithTimeout(1 * time.Second)
defer b.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
// Create two subscribers.
ch1 := make(chan int)
b.Subscribe(ch1)
go func() {
for v := range ch1 {
// Do something.
}
wg.Done()
}()
ch2 := make(chan int)
b.Subscribe(ch2)
go func() {
for v := range ch2 {
// Do another thing.
}
wg.Done()
}()
// Send two value.
b.Chan() <- 1
b.Chan() <- 2
b.Close()
wg.Wait()
Use generics.
"Naive" implementations of broadcast use loop of send statement like this:
for _, c := range subscribers {
c <- v
}
This implementation blocks entire broadcasting when one of the receivers stalls.
To avoid that, use select
statement and add (optional) timeout feature.
Use channel both to send and to receive values, so that select
statement can be used for non-blocking communication.
See GoDoc.
Daisuke (yet another) Maki
MIT License