-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathLockFreeQueueSlow3.h
110 lines (97 loc) · 2.07 KB
/
LockFreeQueueSlow3.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
#pragma once
#include <nstd/Atomic.h>
#include <nstd/Memory.h>
template <typename T> class LockFreeQueueSlow3
{
public:
explicit LockFreeQueueSlow3(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].state = 0;
_tail = 0;
_head = 0;
}
~LockFreeQueueSlow3()
{
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)
{
for(;;)
{
usize tail = _tail;
Node* node = &_queue[tail & _capacityMask];
switch(Atomic::compareAndSwap(node->state, 0, 2))
{
case 2:
continue;
case 0:
break;
default:
return false;
}
if(Atomic::compareAndSwap(_tail, tail, tail + 1) == tail)
{
new (&node->data)T(data);
Atomic::store(node->state, 1);
return true;
}
else
node->state = 0;
}
}
bool pop(T& result)
{
for(;;)
{
usize head = _head;
Node* node = &_queue[head & _capacityMask];
switch(Atomic::compareAndSwap(node->state, 1, 3))
{
case 3:
continue;
case 1:
break;
default:
return false;
}
if(Atomic::compareAndSwap(_head, head, head + 1) == head)
{
result = node->data;
(&node->data)->~T();
Atomic::store(node->state, 0);
return true;
}
else
node->state = 1;
}
}
private:
struct Node
{
T data;
volatile int state;
};
private:
usize _capacityMask;
Node* _queue;
usize _capacity;
char cacheLinePad1[64];
volatile usize _tail;
char cacheLinePad2[64];
volatile usize _head;
char cacheLinePad3[64];
};