-
Notifications
You must be signed in to change notification settings - Fork 45
/
window_manager.go
75 lines (65 loc) · 993 Bytes
/
window_manager.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 muxado
import (
"sync"
)
type windowManager interface {
Increment(int)
Decrement(int) (int, error)
SetError(error)
}
type condWindow struct {
val int
maxSize int
err error
sync.Cond
sync.Mutex
}
func newCondWindow(initialSize int) *condWindow {
w := new(condWindow)
w.Init(initialSize)
return w
}
func (w *condWindow) Init(initialSize int) {
w.val = initialSize
w.maxSize = initialSize
w.Cond.L = &w.Mutex
}
func (w *condWindow) Increment(inc int) {
w.L.Lock()
w.val += inc
w.Broadcast()
w.L.Unlock()
}
func (w *condWindow) SetError(err error) {
w.L.Lock()
w.err = err
w.Broadcast()
w.L.Unlock()
}
func (w *condWindow) Decrement(dec int) (ret int, err error) {
if dec == 0 {
return
}
w.L.Lock()
for {
if w.err != nil {
err = w.err
break
}
if w.val > 0 {
if dec > w.val {
ret = w.val
w.val = 0
break
} else {
ret = dec
w.val -= dec
break
}
} else {
w.Wait()
}
}
w.L.Unlock()
return
}