go-zero/core/syncx/cond.go

50 lines
957 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/core/timex"
2020-07-26 17:09:05 +08:00
)
2021-02-28 16:16:22 +08:00
// A Cond is used to wait for conditions.
2020-07-26 17:09:05 +08:00
type Cond struct {
signal chan lang.PlaceholderType
}
2021-02-28 16:16:22 +08:00
// NewCond returns a Cond.
2020-07-26 17:09:05 +08:00
func NewCond() *Cond {
return &Cond{
signal: make(chan lang.PlaceholderType),
}
}
2021-02-28 16:16:22 +08:00
// WaitWithTimeout wait for signal return remain wait time or timed out.
2020-07-26 17:09:05 +08:00
func (cond *Cond) WaitWithTimeout(timeout time.Duration) (time.Duration, bool) {
timer := time.NewTimer(timeout)
defer timer.Stop()
begin := timex.Now()
select {
case <-cond.signal:
elapsed := timex.Since(begin)
remainTimeout := timeout - elapsed
return remainTimeout, true
case <-timer.C:
return 0, false
}
}
2021-02-28 16:16:22 +08:00
// Wait waits for signals.
2020-07-26 17:09:05 +08:00
func (cond *Cond) Wait() {
<-cond.signal
}
// Signal wakes one goroutine waiting on c, if there is any.
func (cond *Cond) Signal() {
select {
case cond.signal <- lang.Placeholder:
default:
}
}