-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.go
52 lines (44 loc) · 1.03 KB
/
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
package async
import (
"runtime"
"sync/atomic"
)
// NewCountingSemaphore creates a new semaphore with specified amount of available tokens.
func NewCountingSemaphore(size int32) CountingSemaphore {
result := countingSemaphore{size: size}
result.tokens.Store(size)
return &result
}
type countingSemaphore struct {
size int32
tokens atomic.Int32
}
func (l *countingSemaphore) Size() int32 {
return l.size
}
func (l *countingSemaphore) Acquire(count int32) {
for !l.TryAcquire(count) {
runtime.Gosched()
}
}
func (l *countingSemaphore) TryAcquire(count int32) bool {
if l.tokens.Add(count*-1) < 0 {
// acquire failed, cancel the attempt by adding back what was removed
l.tokens.Add(count)
return false
}
return true
}
func (l *countingSemaphore) Release(count int32) {
for !l.TryRelease(count) {
runtime.Gosched()
}
}
func (l *countingSemaphore) TryRelease(count int32) bool {
current := l.tokens.Load()
update := current + count
if update > l.size {
return false
}
return l.tokens.CompareAndSwap(current, update)
}