forked from tangled.org/core
this repo has no description
at master 684 B view raw
1package notifier 2 3import ( 4 "sync" 5) 6 7type Notifier struct { 8 subscribers map[chan struct{}]struct{} 9 mu sync.Mutex 10} 11 12func New() Notifier { 13 return Notifier{ 14 subscribers: make(map[chan struct{}]struct{}), 15 } 16} 17 18func (n *Notifier) Subscribe() chan struct{} { 19 ch := make(chan struct{}, 1) 20 n.mu.Lock() 21 n.subscribers[ch] = struct{}{} 22 n.mu.Unlock() 23 return ch 24} 25 26func (n *Notifier) Unsubscribe(ch chan struct{}) { 27 n.mu.Lock() 28 delete(n.subscribers, ch) 29 close(ch) 30 n.mu.Unlock() 31} 32 33func (n *Notifier) NotifyAll() { 34 n.mu.Lock() 35 for ch := range n.subscribers { 36 select { 37 case ch <- struct{}{}: 38 default: 39 // avoid blocking if channel is full 40 } 41 } 42 n.mu.Unlock() 43}