Skip to content

Instantly share code, notes, and snippets.

@kikuchy
Last active April 13, 2022 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikuchy/92529ce8947a8a1caf7847c135fdbdb2 to your computer and use it in GitHub Desktop.
Save kikuchy/92529ce8947a8a1caf7847c135fdbdb2 to your computer and use it in GitHub Desktop.
Simple broadcast mechanism for multiple goroutines and a channel.
type Broadcaster[T any] struct {
chans []chan T
}
func (b *Broadcaster[T]) Listen() chan T {
c := make(chan T)
b.chans = append(b.chans, c)
return c
}
func (b *Broadcaster[T]) Send(i T) {
for _, c := range b.chans {
c <- i
}
}
func (b *Broadcaster[T]) Close() {
for _, c := range b.chans {
close(c)
}
}
// func main() {
// var wg sync.WaitGroup
// b := new(Broadcaster[int])
// for i := 0; i < 10; i++ {
// wg.Add(1)
// go func(ch chan int) {
// defer wg.Done()
// v := <-ch
// println(v)
// }(b.Listen())
// }
// b.Send(100)
// b.Close()
// wg.Wait()
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment