-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
87 lines (74 loc) · 1.83 KB
/
queue.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
package lock_free
import (
"sync/atomic"
"unsafe"
)
type node[Value any] struct {
next *node[Value]
val Value
}
type LFQueue[Value any] struct {
prev *node[Value]
tail *node[Value]
length int64
}
func NewQueue[Value any]() *LFQueue[Value] {
return &LFQueue[Value]{}
}
func (q *LFQueue[Value]) Push(v Value) {
newNode := &node[Value]{
val: v,
}
if q.Len() == 0 && q.cas(&q.prev, nil, newNode) {
q.inc()
q.swap(&q.tail, newNode)
return
}
for {
if q.load(&q.tail) == nil {
continue
}
swapped := q.cas(&q.tail.next, nil, newNode)
if swapped {
q.inc()
q.store(&q.tail, q.tail.next)
return
}
}
}
func (q *LFQueue[Value]) Pop() (Value, bool) {
if q.load(&q.prev) == nil {
return *new(Value), false
}
for {
old := q.load(&q.prev)
if old == nil {
return *new(Value), false
}
if q.cas(&q.prev, old, old.next) {
q.dec()
return old.val, true
}
}
}
func (q *LFQueue[Value]) load(rootNode **node[Value]) *node[Value] {
return (*node[Value])(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(rootNode))))
}
func (q *LFQueue[Value]) store(rootNode **node[Value], node *node[Value]) {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(rootNode)), unsafe.Pointer(node))
}
func (q *LFQueue[Value]) cas(rootNode **node[Value], old, new *node[Value]) bool {
return atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(rootNode)), unsafe.Pointer(old), unsafe.Pointer(new))
}
func (q *LFQueue[Value]) swap(rootNode **node[Value], new *node[Value]) (old *node[Value]) {
return (*node[Value])(atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(rootNode)), unsafe.Pointer(new)))
}
func (q *LFQueue[Value]) Len() int {
return int(atomic.LoadInt64(&q.length))
}
func (q *LFQueue[Value]) inc() {
atomic.AddInt64(&q.length, 1)
}
func (q *LFQueue[Value]) dec() {
atomic.AddInt64(&q.length, -1)
}