A golang channel broadcaster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
788 B

package broadcast
import (
"sync"
)
type Broadcast struct {
channels []chan interface{}
channelLock sync.Mutex
}
func (b *Broadcast) Subscribe() chan interface{} {
b.channelLock.Lock()
defer b.channelLock.Unlock()
newChannel := make(chan interface{})
b.channels = append(b.channels, newChannel)
return newChannel
}
func (b *Broadcast) WaitNext() interface{} {
return <-b.Subscribe()
}
func (b *Broadcast) Send(value interface{}) {
wg := sync.WaitGroup{}
b.channelLock.Lock()
for _, channel := range b.channels {
wg.Add(1)
//Do not use closure as reference will change
go func(thisChannel chan<- interface{}) {
thisChannel <- value
wg.Done()
}(channel)
}
b.channelLock.Unlock()
wg.Wait()
}
func (b *Broadcast) Count() int {
return len(b.channels)
}