cond.go 879 B

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