chancond.go 493 B

123456789101112131415161718192021222324252627282930313233343536
  1. package missinggo
  2. import "sync"
  3. type ChanCond struct {
  4. mu sync.Mutex
  5. ch chan struct{}
  6. }
  7. func (me *ChanCond) Wait() <-chan struct{} {
  8. me.mu.Lock()
  9. defer me.mu.Unlock()
  10. if me.ch == nil {
  11. me.ch = make(chan struct{})
  12. }
  13. return me.ch
  14. }
  15. func (me *ChanCond) Signal() {
  16. me.mu.Lock()
  17. defer me.mu.Unlock()
  18. select {
  19. case me.ch <- struct{}{}:
  20. default:
  21. }
  22. }
  23. func (me *ChanCond) Broadcast() {
  24. me.mu.Lock()
  25. defer me.mu.Unlock()
  26. if me.ch == nil {
  27. return
  28. }
  29. close(me.ch)
  30. me.ch = nil
  31. }