broadcast-cond.go.go 817 B

12345678910111213141516171819202122232425262728293031323334
  1. package chansync
  2. import (
  3. "github.com/anacrolix/chansync/events"
  4. "github.com/anacrolix/sync"
  5. )
  6. // Can be used as zero-value. Due to the caller needing to bring their own synchronization, an
  7. // equivalent to "sync".Cond.Signal is not provided. BroadcastCond is intended to be selected on
  8. // with other channels.
  9. type BroadcastCond struct {
  10. mu sync.Mutex
  11. ch chan struct{}
  12. }
  13. func (me *BroadcastCond) Broadcast() {
  14. me.mu.Lock()
  15. defer me.mu.Unlock()
  16. if me.ch != nil {
  17. close(me.ch)
  18. me.ch = nil
  19. }
  20. }
  21. // Should be called before releasing locks on resources that might trigger subsequent Broadcasts.
  22. // The channel is closed when the condition changes.
  23. func (me *BroadcastCond) Signaled() events.Signaled {
  24. me.mu.Lock()
  25. defer me.mu.Unlock()
  26. if me.ch == nil {
  27. me.ch = make(chan struct{})
  28. }
  29. return me.ch
  30. }