...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package wait
16
17 import "sync"
18
19 type WaitTime interface {
20
21
22
23 Wait(deadline uint64) <-chan struct{}
24
25 Trigger(deadline uint64)
26 }
27
28 var closec chan struct{}
29
30 func init() { closec = make(chan struct{}); close(closec) }
31
32 type timeList struct {
33 l sync.Mutex
34 lastTriggerDeadline uint64
35 m map[uint64]chan struct{}
36 }
37
38 func NewTimeList() *timeList {
39 return &timeList{m: make(map[uint64]chan struct{})}
40 }
41
42 func (tl *timeList) Wait(deadline uint64) <-chan struct{} {
43 tl.l.Lock()
44 defer tl.l.Unlock()
45 if tl.lastTriggerDeadline >= deadline {
46 return closec
47 }
48 ch := tl.m[deadline]
49 if ch == nil {
50 ch = make(chan struct{})
51 tl.m[deadline] = ch
52 }
53 return ch
54 }
55
56 func (tl *timeList) Trigger(deadline uint64) {
57 tl.l.Lock()
58 defer tl.l.Unlock()
59 tl.lastTriggerDeadline = deadline
60 for t, ch := range tl.m {
61 if t <= deadline {
62 delete(tl.m, t)
63 close(ch)
64 }
65 }
66 }
67
View as plain text