-
Notifications
You must be signed in to change notification settings - Fork 314
/
completion_barriers.go
124 lines (108 loc) · 2.39 KB
/
completion_barriers.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"sync"
"sync/atomic"
"time"
)
type completionBarrier interface {
completed() float64
tryGrabWork() bool
jobDone()
done() <-chan struct{}
cancel()
}
type countingCompletionBarrier struct {
numReqs, reqsGrabbed, reqsDone uint64
doneChan chan struct{}
closeOnce sync.Once
}
func newCountingCompletionBarrier(numReqs uint64) completionBarrier {
c := new(countingCompletionBarrier)
c.reqsDone, c.reqsGrabbed, c.numReqs = 0, 0, numReqs
c.doneChan = make(chan struct{})
return completionBarrier(c)
}
func (c *countingCompletionBarrier) tryGrabWork() bool {
select {
case <-c.doneChan:
return false
default:
reqsDone := atomic.AddUint64(&c.reqsGrabbed, 1)
return reqsDone <= c.numReqs
}
}
func (c *countingCompletionBarrier) jobDone() {
reqsDone := atomic.AddUint64(&c.reqsDone, 1)
if reqsDone == c.numReqs {
c.closeOnce.Do(func() {
close(c.doneChan)
})
}
}
func (c *countingCompletionBarrier) done() <-chan struct{} {
return c.doneChan
}
func (c *countingCompletionBarrier) cancel() {
c.closeOnce.Do(func() {
close(c.doneChan)
})
}
func (c *countingCompletionBarrier) completed() float64 {
select {
case <-c.doneChan:
return 1.0
default:
reqsDone := atomic.LoadUint64(&c.reqsDone)
return float64(reqsDone) / float64(c.numReqs)
}
}
type timedCompletionBarrier struct {
doneChan chan struct{}
closeOnce sync.Once
start time.Time
duration time.Duration
}
func newTimedCompletionBarrier(duration time.Duration) completionBarrier {
if duration < 0 {
panic("timedCompletionBarrier: negative duration")
}
c := new(timedCompletionBarrier)
c.doneChan = make(chan struct{})
c.start = time.Now()
c.duration = duration
go func() {
time.AfterFunc(duration, func() {
c.closeOnce.Do(func() {
close(c.doneChan)
})
})
}()
return completionBarrier(c)
}
func (c *timedCompletionBarrier) tryGrabWork() bool {
select {
case <-c.doneChan:
return false
default:
return true
}
}
func (c *timedCompletionBarrier) jobDone() {
}
func (c *timedCompletionBarrier) done() <-chan struct{} {
return c.doneChan
}
func (c *timedCompletionBarrier) cancel() {
c.closeOnce.Do(func() {
close(c.doneChan)
})
}
func (c *timedCompletionBarrier) completed() float64 {
select {
case <-c.doneChan:
return 1.0
default:
return float64(time.Since(c.start).Nanoseconds()) /
float64(c.duration.Nanoseconds())
}
}