-
Notifications
You must be signed in to change notification settings - Fork 38
/
LockFreeLifoQueue.h
119 lines (104 loc) · 2.47 KB
/
LockFreeLifoQueue.h
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
#pragma once
#include <nstd/Atomic.h>
#include <nstd/Memory.h>
template <typename T> class LockFreeLifoQueue
{
public:
explicit LockFreeLifoQueue(usize capacity)
: _capacity(capacity)
{
_indexMask = capacity;
for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1)
_indexMask |= _indexMask >> i;
_abaOffset = _indexMask + 1;
_queue = (Node*)Memory::alloc(sizeof(Node) * (capacity + 1));
for(usize i = 1; i < capacity;)
{
Node& node = _queue[i];
node.abaNextFree = ++i;
}
_queue[capacity].abaNextFree = 0;
_abaFree = 1;
_abaPushed = 0;
}
~LockFreeLifoQueue()
{
for(usize abaPushed = _abaPushed;;)
{
usize nodeIndex = abaPushed & _indexMask;
if(!nodeIndex)
break;
Node& node = _queue[nodeIndex];
abaPushed = node.abaNextPushed;
(&node.data)->~T();
}
Memory::free(_queue);
}
usize capacity() const {return _capacity;}
usize size() const {return 0;}
bool push(const T& data)
{
Node* node;
usize abaFree;
for(;;)
{
abaFree = _abaFree;
usize nodeIndex = abaFree & _indexMask;
if(!nodeIndex)
return false;
node = &_queue[nodeIndex];
if(Atomic::compareAndSwap(_abaFree, abaFree, node->abaNextFree + _abaOffset) == abaFree)
break;
}
new (&node->data)T(data);
for(;;)
{
usize abaPushed = _abaPushed;
node->abaNextPushed = abaPushed;
if(Atomic::compareAndSwap(_abaPushed, abaPushed, abaFree) == abaPushed)
return true;
}
}
bool pop(T& result)
{
Node* node;
usize abaPushed;
for(;;)
{
abaPushed = _abaPushed;
usize nodeIndex = abaPushed & _indexMask;
if(!nodeIndex)
return false;
node = &_queue[nodeIndex];
if(Atomic::compareAndSwap(_abaPushed, abaPushed, node->abaNextPushed + _abaOffset) == abaPushed)
break;
}
result = node->data;
(&node->data)->~T();
abaPushed += _abaOffset;
for(;;)
{
usize abaFree = _abaFree;
node->abaNextFree = abaFree;
if(Atomic::compareAndSwap(_abaFree, abaFree, abaPushed) == abaFree)
return true;
}
}
private:
struct Node
{
T data;
volatile usize abaNextFree;
volatile usize abaNextPushed;
};
private:
usize _indexMask;
Node* _queue;
usize _abaOffset;
usize _capacity;
char cacheLinePad1[64];
volatile usize _abaFree;
char cacheLinePad2[64];
volatile usize _abaPushed;
char cacheLinePad3[64];
};