cond.go 951 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package syncx
  2. import (
  3. "time"
  4. "git.i2edu.net/i2/go-zero/core/lang"
  5. "git.i2edu.net/i2/go-zero/core/timex"
  6. )
  7. // A Cond is used to wait for conditions.
  8. type Cond struct {
  9. signal chan lang.PlaceholderType
  10. }
  11. // NewCond returns a Cond.
  12. func NewCond() *Cond {
  13. return &Cond{
  14. signal: make(chan lang.PlaceholderType),
  15. }
  16. }
  17. // WaitWithTimeout wait for signal return remain wait time or timed out.
  18. func (cond *Cond) WaitWithTimeout(timeout time.Duration) (time.Duration, bool) {
  19. timer := time.NewTimer(timeout)
  20. defer timer.Stop()
  21. begin := timex.Now()
  22. select {
  23. case <-cond.signal:
  24. elapsed := timex.Since(begin)
  25. remainTimeout := timeout - elapsed
  26. return remainTimeout, true
  27. case <-timer.C:
  28. return 0, false
  29. }
  30. }
  31. // Wait waits for signals.
  32. func (cond *Cond) Wait() {
  33. <-cond.signal
  34. }
  35. // Signal wakes one goroutine waiting on c, if there is any.
  36. func (cond *Cond) Signal() {
  37. select {
  38. case cond.signal <- lang.Placeholder:
  39. default:
  40. }
  41. }