-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathelastic_semaphore.go
109 lines (102 loc) · 1.75 KB
/
elastic_semaphore.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
package kaburaya
import (
"sync"
)
type elasticSemaphore struct {
limit int
counter int
mu *sync.Mutex
waitChan chan struct{}
signalChan chan struct{}
waiting bool
}
func newElasticSemaphore(limit int) *elasticSemaphore {
return &elasticSemaphore{
limit: limit,
counter: limit,
mu: &sync.Mutex{},
waitChan: make(chan struct{}),
signalChan: make(chan struct{}),
waiting: false,
}
}
func (es *elasticSemaphore) wait() {
WAIT:
es.mu.Lock()
if es.counter <= 0 {
es.counter--
es.waiting = true
es.mu.Unlock()
es.waitChan <- struct{}{}
<-es.signalChan
es.mu.Lock()
if es.counter < 0 {
es.mu.Unlock()
goto WAIT
}
es.mu.Unlock()
return
}
es.waiting = false
es.counter--
es.mu.Unlock()
return
}
func (es *elasticSemaphore) signal() {
WAIT:
es.mu.Lock()
doSignal := false
if es.waiting && es.counter == -1 {
select {
case <-es.waitChan:
default:
es.mu.Unlock()
goto WAIT
}
doSignal = true
}
if es.limit >= es.counter+1 {
es.counter++
} else {
es.counter = es.limit
}
if doSignal {
es.signalChan <- struct{}{}
}
es.mu.Unlock()
}
func (es *elasticSemaphore) incrementLimit(n int) int {
if n == 0 {
return es.limit
}
WAIT:
es.mu.Lock()
if n > 0 {
doSignal := false
if es.waiting && (es.counter == -1 || (es.counter < 0 && es.counter+n > 0)) {
select {
case <-es.waitChan:
default:
es.mu.Unlock()
goto WAIT
}
doSignal = true
}
es.counter += n
es.limit += n
if doSignal {
es.signalChan <- struct{}{}
}
} else {
newLimit := es.limit + n
if newLimit < 1 {
newLimit = 1
}
if es.limit != newLimit {
es.counter = newLimit - (es.limit - es.counter)
}
es.limit = newLimit
}
defer es.mu.Unlock()
return es.limit
}