-
Notifications
You must be signed in to change notification settings - Fork 0
/
chanSema.go
76 lines (63 loc) · 1.32 KB
/
chanSema.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
// (C)Tylor Arndt 2014, Mozilla Public License (MPL) Version 2.0
// See LICENSE file for details.
// For other licensing options please contact the author.
package sema
//chanSema is channel-based counting semaphore implementation
type chanSema chan struct{}
//NewChanSema constructs a new binary semaphore
func NewChanSema() Semaphore {
newChanSema := make(chanSema, 1)
newChanSema.V()
return newChanSema
}
//NewChanSemaCount constructs a new counting semaphore
func NewChanSemaCount(count uint) CountingSema {
newChanSema := make(chanSema, count)
newChanSema.Signal(count)
return newChanSema
}
func (s chanSema) Capacity() uint {
return uint(cap(s))
}
func (s chanSema) P() bool {
<-s
return true
}
func (s chanSema) Acquire() bool {
return s.P()
}
func (s chanSema) Wait(units uint) bool {
total := units
for ; units > 0; units-- {
select {
case <-s:
default:
if actual := total - units; actual > 0 {
s.Signal(actual)
}
return false
}
}
return true
}
func (s chanSema) V() bool {
s <- struct{}{}
return true
}
func (s chanSema) Release() bool {
return s.V()
}
func (s chanSema) Signal(units uint) bool {
total := units
for ; units > 0; units-- {
select {
case s <- struct{}{}:
default:
if actual := total - units; actual > 0 {
s.Wait(actual)
}
return false
}
}
return true
}