Browse Source

made broadcasts threadsafe

main v0.0.1
Pixdigit 1 year ago
parent
commit
c1b1e93c67
  1. 7
      broadcast.go

7
broadcast.go

@ -6,9 +6,12 @@ import (
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
@ -21,6 +24,8 @@ func (b *Broadcast) WaitNext() interface{} {
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
@ -30,6 +35,8 @@ func (b *Broadcast) Send(value interface{}) {
}(channel)
}
b.channelLock.Unlock()
wg.Wait()
}

Loading…
Cancel
Save