Last active
April 13, 2022 12:47
-
-
Save kikuchy/92529ce8947a8a1caf7847c135fdbdb2 to your computer and use it in GitHub Desktop.
Simple broadcast mechanism for multiple goroutines and a channel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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