You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/syncx/cond.go

50 lines
957 B
Go

4 years ago
package syncx
import (
"time"
"github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/core/timex"
4 years ago
)
// A Cond is used to wait for conditions.
4 years ago
type Cond struct {
signal chan lang.PlaceholderType
}
// NewCond returns a Cond.
4 years ago
func NewCond() *Cond {
return &Cond{
signal: make(chan lang.PlaceholderType),
}
}
// WaitWithTimeout wait for signal return remain wait time or timed out.
4 years ago
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
}
}
// Wait waits for signals.
4 years ago
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:
}
}