-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXPQueue.go
141 lines (120 loc) · 2.31 KB
/
XPQueue.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package XPSuperKit
import (
"runtime"
"sync/atomic"
)
type queueCache struct {
value interface{}
mark bool
}
// lock free queue
type XPQueueImpl struct {
capacity uint32
capMod uint32
putPos uint32
getPos uint32
cache []queueCache
}
func NewXPQueue(capacity uint32) *XPQueueImpl {
q := new(XPQueueImpl)
q.capacity = minQuantity(capacity)
q.capMod = q.capacity - 1
q.cache = make([]queueCache, q.capacity)
return q
}
func (q *XPQueueImpl) Capacity() uint32 {
return q.capacity
}
// round 到最近的2的倍数
func minQuantity(v uint32) uint32 {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}
func (q *XPQueueImpl) Count() uint32 {
var putPos, getPos uint32
var quantity uint32
getPos = q.getPos
putPos = q.putPos
if putPos >= getPos {
quantity = putPos - getPos
} else {
quantity = q.capMod + putPos - getPos
}
return quantity
}
// put queue functions
func (q *XPQueueImpl) Put(val interface{}) (ok bool, count uint32) {
var putPos, putPosNew, getPos, posCnt uint32
var cache *queueCache
capMod := q.capMod
for {
getPos = q.getPos
putPos = q.putPos
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + putPos - getPos
}
if posCnt >= capMod {
runtime.Gosched()
return false, posCnt
}
putPosNew = putPos + 1
if atomic.CompareAndSwapUint32(&q.putPos, putPos, putPosNew) {
break
} else {
runtime.Gosched()
}
}
cache = &q.cache[putPosNew&capMod]
for {
if !cache.mark {
cache.value = val
cache.mark = true
return true, posCnt + 1
} else {
runtime.Gosched()
}
}
}
// get queue functions
func (q *XPQueueImpl) Get() (val interface{}, ok bool, count uint32) {
var putPos, getPos, getPosNew, posCnt uint32
var cache *queueCache
capMod := q.capMod
for {
putPos = q.putPos
getPos = q.getPos
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + putPos - getPos
}
if posCnt < 1 {
runtime.Gosched()
return nil, false, posCnt
}
getPosNew = getPos + 1
if atomic.CompareAndSwapUint32(&q.getPos, getPos, getPosNew) {
break
} else {
runtime.Gosched()
}
}
cache = &q.cache[getPosNew&capMod]
for {
if cache.mark {
val = cache.value
cache.mark = false
return val, true, posCnt - 1
} else {
runtime.Gosched()
}
}
}