-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcond.go
76 lines (66 loc) · 1.73 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package zlog
import (
"sync"
"time"
)
// TimeoutCond is a sync.Cond improve for support wait timeout.
type TimeoutCond struct {
L sync.Locker
signal chan int
hasWaiters bool
}
// NewTimeoutCond return a new TimeoutCond
func NewTimeoutCond(l sync.Locker) *TimeoutCond {
cond := TimeoutCond{L: l, signal: make(chan int, 0)}
return &cond
}
// WaitWithTimeout wait for signal return remain wait time, and is interrupted
func (cond *TimeoutCond) WaitWithTimeout(timeout time.Duration) (time.Duration, bool) {
cond.setHasWaiters(true)
ch := cond.signal
//wait should unlock mutex, if not will cause deadlock
cond.L.Unlock()
defer cond.setHasWaiters(false)
defer cond.L.Lock()
begin := time.Now().UnixNano()
select {
case _, ok := <-ch:
end := time.Now().UnixNano()
remainTimeout := timeout - time.Duration(end-begin)
return remainTimeout, !ok
case <-time.After(timeout):
return 0, false
}
}
func (cond *TimeoutCond) setHasWaiters(value bool) {
cond.hasWaiters = value
}
// HasWaiters queries whether any goroutine are waiting on this condition
func (cond *TimeoutCond) HasWaiters() bool {
return cond.hasWaiters
}
// Wait for signal return waiting is interrupted
func (cond *TimeoutCond) Wait() bool {
cond.setHasWaiters(true)
//copy signal in lock, avoid data race with Interrupt
ch := cond.signal
cond.L.Unlock()
defer cond.setHasWaiters(false)
defer cond.L.Lock()
_, ok := <-ch
return !ok
}
// Signal wakes one goroutine waiting on c, if there is any.
func (cond *TimeoutCond) Signal() {
select {
case cond.signal <- 1:
default:
}
}
// Interrupt goroutine wait on this TimeoutCond
func (cond *TimeoutCond) Interrupt() {
cond.L.Lock()
defer cond.L.Unlock()
close(cond.signal)
cond.signal = make(chan int, 0)
}