-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate_holders.go
83 lines (64 loc) · 1.56 KB
/
state_holders.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
package occamy
import (
"sync/atomic"
)
// region Atomic Int
type atomicInt struct {
value *int32
}
func newAtomicInt(initial int) atomicInt {
i := atomicInt{value: new(int32)}
atomic.AddInt32(i.value, int32(initial))
return i
}
func (i *atomicInt) decrease() {
atomic.AddInt32(i.value, -1)
}
func (i *atomicInt) increase() {
atomic.AddInt32(i.value, 1)
}
func (i *atomicInt) isEqual(other int) bool {
return atomic.LoadInt32(i.value) == int32(other)
}
func (i *atomicInt) load() int {
value := atomic.LoadInt32(i.value)
return int(value)
}
// endregion
// region Semaphore
// semaphore is used to record a state. It can either be in the activated or
// deactivated state. It is NOT thread safe. It is up to the user to ensure that
// data is never modified or read simultaneously.
type semaphore struct {
ch chan struct{} // ch is closed when deactivated and not closed when activated
state int32 // state is 0 when deactivated and 1 when activated
}
func newSemaphore(activated bool) *semaphore {
semaphore := &semaphore{
ch: make(chan struct{}),
state: 1,
}
if !activated {
semaphore.deactivate()
}
return semaphore
}
func (s *semaphore) activate() {
if atomic.LoadInt32(&s.state) == 0 {
s.ch = make(chan struct{})
atomic.StoreInt32(&s.state, 1)
}
}
func (s *semaphore) deactivate() {
if atomic.LoadInt32(&s.state) == 1 {
close(s.ch)
atomic.StoreInt32(&s.state, 0)
}
}
func (s *semaphore) isActive() bool {
return atomic.LoadInt32(&s.state) == 1
}
func (s *semaphore) deactivatedCh() <-chan struct{} {
return s.ch
}
// endregion