forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cond.go
49 lines (41 loc) · 951 Bytes
/
cond.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package syncx
import (
"time"
"github.com/r00mz/go-zero/core/lang"
"github.com/r00mz/go-zero/core/timex"
)
// A Cond is used to wait for conditions.
type Cond struct {
signal chan lang.PlaceholderType
}
// NewCond returns a Cond.
func NewCond() *Cond {
return &Cond{
signal: make(chan lang.PlaceholderType),
}
}
// WaitWithTimeout wait for signal return remain wait time or timed out.
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.
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:
}
}