-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc.go
104 lines (86 loc) · 1.83 KB
/
c.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
package concr
import (
"sync/atomic"
"time"
"unsafe"
)
type C struct {
state uint64
idle unsafe.Pointer
}
func (c *C) Inc() uint32 {
n := atomic.AddUint64(&c.state, 1)
v := n & valueMask
if v == 1 {
for !atomic.CompareAndSwapUint64(&c.state, n, n|waitLock) {
}
}
return uint32(v)
}
func (c *C) Dec() uint32 {
return uint32(atomic.AddUint64(&c.state, ^uint64(0)) & valueMask)
}
func (c *C) Get() (uint32, uint32) {
n := atomic.LoadUint64(&c.state)
return uint32(n & valueMask), uint32(n & limitMask >> 31)
}
func (c *C) Set(m uint32) {
var n uint64
for {
n = atomic.LoadUint64(&c.state)
if atomic.CompareAndSwapUint64(&c.state, n, n&(valueMask|waitLock)|uint64(m)<<31) {
return
}
}
}
func (c *C) Within() bool {
n := atomic.LoadUint64(&c.state)
return n&valueMask < n&limitMask>>31
}
func (c *C) Reached() bool {
n := atomic.LoadUint64(&c.state)
v := n & valueMask
return v > 0 && v == n&limitMask>>31
}
func (c *C) Exceeded() bool {
n := atomic.LoadUint64(&c.state)
v := n & valueMask
return v > 0 && v > n&limitMask>>31
}
func (c *C) Wait() {
var v uint64
for {
c.Idle()
v = atomic.LoadUint64(&c.state)
if v&waitLock == 0 {
continue
}
if v&valueMask == 0 {
break
}
}
for !atomic.CompareAndSwapUint64(&c.state, v, v|waitLock^waitLock) {
}
}
func (c *C) Idle() {
p := atomic.LoadPointer(&c.idle)
if p == nil {
p = unsafe.Pointer(&defaultIdle)
atomic.StorePointer(&c.idle, p)
}
(*(*func())(p))()
}
func (c *C) SetIdle(f func()) {
if f == nil {
f = defaultIdle
}
atomic.StorePointer(&c.idle, unsafe.Pointer(&f))
}
var defaultIdle = func() { time.Sleep(time.Duration(100 * time.Millisecond)) }
const (
MAX = uint64(1<<30 - 1)
// 1001111111111111111111111111111110111111111111111111111111111111
valueMask = MAX
limitMask = uint64(valueMask << 31)
waitLock = uint64(1 << 63)
)