-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathLockFreeQueueSlow2.h
116 lines (103 loc) · 2.34 KB
/
LockFreeQueueSlow2.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
#pragma once
#include <nstd/Atomic.h>
#include <nstd/Memory.h>
template <typename T> class LockFreeQueueSlow2
{
public:
explicit LockFreeQueueSlow2(usize capacity)
{
_capacityMask = capacity - 1;
for(usize i = 1; i <= sizeof(void*) * 4; i <<= 1)
_capacityMask |= _capacityMask >> i;
_capacity = _capacityMask + 1;
_queue = (Node*)Memory::alloc(sizeof(Node) * _capacity);
for(usize i = 0; i < _capacity; ++i)
{
_queue[i].tail = i;
_queue[i].head = i - 1;
}
_tail = 0;
_head = 0;
}
~LockFreeQueueSlow2()
{
for(usize i = _head; i != _tail; ++i)
(&_queue[i & _capacityMask].data)->~T();
Memory::free(_queue);
}
usize capacity() const {return _capacity;}
usize size() const
{
usize head = Atomic::load(_head);
return _tail - head;
}
bool push(const T& data)
{
begin:
usize tail = _tail;
Node* node = &_queue[tail & _capacityMask];
usize newTail = tail + 1;
usize nodeTail = node->tail;
if(nodeTail == tail)
{
nodeTail = Atomic::compareAndSwap(node->tail, tail, newTail);
if(nodeTail == tail)
{
Atomic::compareAndSwap(_tail, tail, newTail);
new (&node->data)T(data);
Atomic::store(node->head, tail);
return true;
}
}
if(nodeTail == newTail)
{
Atomic::compareAndSwap(_tail, tail, newTail);
goto begin;
}
else
return false;
}
bool pop(T& result)
{
begin:
usize head = _head;
Node* node = &_queue[head & _capacityMask];
usize newHead = head + 1;
usize nodeHead = node->head;
if(nodeHead == head)
{
nodeHead = Atomic::compareAndSwap(node->head, head, newHead);
if(nodeHead == head)
{
Atomic::compareAndSwap(_head, head, newHead);
result = node->data;
(&node->data)->~T();
Atomic::store(node->tail, head + _capacity);
return true;
}
}
if(nodeHead == newHead)
{
Atomic::compareAndSwap(_head, head, newHead);
goto begin;
}
else
return false;
}
private:
struct Node
{
T data;
volatile usize head;
volatile usize tail;
};
private:
usize _capacityMask;
Node* _queue;
usize _capacity;
char cacheLinePad1[64];
volatile usize _head;
char cacheLinePad2[64];
volatile usize _tail;
char cacheLinePad3[64];
};