You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

counter_cond.go 633 B

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package sync2
  2. import "sync"
  3. type CounterCond struct {
  4. count int
  5. cond *sync.Cond
  6. }
  7. func NewCounterCond(initCount int) *CounterCond {
  8. return &CounterCond{
  9. count: initCount,
  10. cond: sync.NewCond(&sync.Mutex{}),
  11. }
  12. }
  13. func (c *CounterCond) Wait() bool {
  14. c.cond.L.Lock()
  15. defer c.cond.L.Unlock()
  16. for c.count == 0 {
  17. c.cond.Wait()
  18. if c.count == 0 {
  19. return false
  20. }
  21. }
  22. c.count--
  23. return true
  24. }
  25. func (c *CounterCond) Release() {
  26. c.cond.L.Lock()
  27. c.count++
  28. c.cond.L.Unlock()
  29. c.cond.Signal()
  30. }
  31. // WakeupAll 不改变计数状态,唤醒所有等待线程
  32. func (c *CounterCond) WakeupAll() {
  33. c.cond.Broadcast()
  34. }