-
Notifications
You must be signed in to change notification settings - Fork 0
/
cond.go
75 lines (66 loc) · 1.19 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
package copper
import (
"sync"
"time"
)
type expiration struct {
t *time.Timer
cond *sync.Cond
expired bool
}
func newExpiration(cond *sync.Cond, d time.Duration) *expiration {
e := &expiration{
cond: cond,
}
e.t = time.AfterFunc(d, e.callback)
return e
}
func (e *expiration) callback() {
e.cond.L.Lock()
defer e.cond.L.Unlock()
if !e.expired {
e.expired = true
e.cond.Broadcast()
}
}
func (e *expiration) stop() bool {
if e.t != nil {
return e.t.Stop()
}
return false
}
type condWithDeadline struct {
sync.Cond
deadline time.Time
exp *expiration
}
func (c *condWithDeadline) init(lock sync.Locker) {
c.Cond.L = lock
}
func (c *condWithDeadline) setDeadline(t time.Time) {
if c.deadline != t {
if c.exp != nil {
c.exp.stop()
c.exp = nil
}
c.deadline = t
if !t.IsZero() {
// Since deadline has changed Wait needs to wake up and recheck
c.Broadcast()
}
}
}
func (c *condWithDeadline) Wait() error {
if c.exp == nil && !c.deadline.IsZero() {
d := c.deadline.Sub(time.Now())
if d <= 0 {
return errTimeout
}
c.exp = newExpiration(&c.Cond, d)
}
c.Cond.Wait()
if c.exp != nil && c.exp.expired {
return errTimeout
}
return nil
}