notifier.go 791 B

12345678910111213141516171819202122232425262728293031323334
  1. package signal
  2. import "sync"
  3. // Notifier is a utility for notifying changes. The change producer may notify changes multiple time, and the consumer may get notified asynchronously.
  4. type Notifier struct {
  5. sync.Mutex
  6. waiters []chan struct{}
  7. }
  8. // NewNotifier creates a new Notifier.
  9. func NewNotifier() *Notifier {
  10. return &Notifier{}
  11. }
  12. // Signal signals a change, usually by producer. This method never blocks.
  13. func (n *Notifier) Signal() {
  14. n.Lock()
  15. for _, w := range n.waiters {
  16. close(w)
  17. }
  18. n.waiters = make([]chan struct{}, 0, 8)
  19. n.Unlock()
  20. }
  21. // Wait returns a channel for waiting for changes. The returned channel never gets closed.
  22. func (n *Notifier) Wait() <-chan struct{} {
  23. n.Lock()
  24. defer n.Unlock()
  25. w := make(chan struct{})
  26. n.waiters = append(n.waiters, w)
  27. return w
  28. }