/
l.go
80 lines (71 loc) · 1.24 KB
/
l.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
package alloclim
import "sync"
// Manages reservations sharing a common allocation limit.
type Limiter struct {
// Maximum outstanding allocation space.
Max int64
initOnce sync.Once
mu sync.Mutex
// Current unallocated space.
value int64
// Reservations waiting to in the order they arrived.
waiting []*Reservation
}
func (me *Limiter) initValue() {
me.value = me.Max
}
func (me *Limiter) init() {
me.initOnce.Do(func() {
me.initValue()
})
}
func (me *Limiter) Reserve(n int64) *Reservation {
r := &Reservation{
l: me,
n: n,
}
me.init()
me.mu.Lock()
if n <= me.value {
me.value -= n
r.granted.Set()
} else {
me.waiting = append(me.waiting, r)
}
me.mu.Unlock()
return r
}
func (me *Limiter) doWakesLocked() {
for {
if len(me.waiting) == 0 {
break
}
r := me.waiting[0]
switch {
case r.cancelled.IsSet():
case r.n <= me.value:
if r.wake() {
me.value -= r.n
}
default:
return
}
me.waiting = me.waiting[1:]
}
}
func (me *Limiter) doWakes() {
me.mu.Lock()
me.doWakesLocked()
me.mu.Unlock()
}
func (me *Limiter) addValue(n int64) {
me.mu.Lock()
me.value += n
me.doWakesLocked()
me.mu.Unlock()
}
func (me *Limiter) Value() int64 {
me.mu.Lock()
defer me.mu.Unlock()
return me.value
}