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 597 B

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142
  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.count++
  27. c.cond.Signal()
  28. }
  29. // WakeupAll 不改变计数状态,唤醒所有等待线程
  30. func (c *CounterCond) WakeupAll() {
  31. c.cond.Broadcast()
  32. }