-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomicqueue.go
More file actions
125 lines (96 loc) · 1.81 KB
/
Copy pathatomicqueue.go
File metadata and controls
125 lines (96 loc) · 1.81 KB
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
package unboundedchannel
import (
"errors"
"sync"
"sync/atomic"
)
// unused, found locked queue provide better perf actually..
var ErrQueueClosed = errors.New("queue already closed")
type qNode[T any] struct {
val T
next atomic.Pointer[qNode[T]]
}
type Queue[T any] struct {
dummy qNode[T]
head atomic.Pointer[qNode[T]]
tail atomic.Pointer[qNode[T]]
len atomic.Int64
pool *sync.Pool
cond *sync.Cond
closed atomic.Bool
}
func NewQueue[T any]() *Queue[T] {
var q Queue[T]
q.head.Store(&q.dummy)
q.tail.Store(q.head.Load())
q.pool = &sync.Pool{
New: func() any {
return &qNode[T]{}
},
}
q.cond = sync.NewCond(&sync.Mutex{})
return &q
}
func (q *Queue[T]) Len() int {
return int(q.len.Load())
}
func (q *Queue[T]) Pop() (T, bool, error) {
return q.pop(false)
}
func (q *Queue[T]) PopWait() (T, bool, error) {
return q.pop(true)
}
func (q *Queue[T]) pop(wait bool) (T, bool, error) {
for {
head := q.head.Load()
next := head.next.Load()
if next != nil {
if q.head.CompareAndSwap(head, next) {
q.len.Add(-1)
v := next.val
*head = qNode[T]{}
q.pool.Put(head)
return v, true, nil
} else {
continue
}
} else {
if q.closed.Load() {
var v T
return v, false, ErrQueueClosed
}
if wait {
q.cond.L.Lock()
if q.len.Load() == 0 {
q.cond.Wait()
}
q.cond.L.Unlock()
continue
}
var v T
return v, false, nil
}
}
}
func (q *Queue[T]) Push(val T) error {
if q.closed.Load() {
return ErrQueueClosed
}
node := q.pool.Get().(*qNode[T])
*node = qNode[T]{val: val}
for {
tail := q.tail.Load()
if tail.next.CompareAndSwap(nil, node) {
q.tail.Store(node)
q.len.Add(1)
q.cond.Signal()
return nil
} else {
continue
}
}
}
func (q *Queue[T]) Close() {
q.closed.Store(true)
q.cond.Broadcast()
}