-
Notifications
You must be signed in to change notification settings - Fork 38
/
SpinLockQueue.h
84 lines (72 loc) · 1.56 KB
/
SpinLockQueue.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
#pragma once
#include <nstd/Atomic.h>
#include <nstd/Memory.h>
template <typename T> class SpinLockQueue
{
public:
explicit SpinLockQueue(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);
_lock = 0;
_head = 0;
_tail = 0;
}
~SpinLockQueue()
{
for(usize i = _head; i != _tail; ++i)
(&_queue[i & _capacityMask].data)->~T();
Memory::free(_queue);
}
usize capacity() const {return _capacity;}
usize size() const
{
usize result;
while(Atomic::testAndSet(_lock) != 0);
result = _tail - _head;
Atomic::store(_lock, 0);
return result;
}
bool push(const T& data)
{
while(Atomic::testAndSet(_lock) != 0);
if(_tail - _head == _capacity)
{
_lock = 0;
return false; // queue is full
}
Node& node = _queue[(_tail++) & _capacityMask];
new (&node.data)T(data);
Atomic::store(_lock, 0);
return true;
}
bool pop(T& result)
{
while(Atomic::testAndSet(_lock) != 0);
if(_head == _tail)
{
_lock = 0;
return false; // queue is empty
}
Node& node = _queue[(_head++) & _capacityMask];
result = node.data;
(&node.data)->~T();
Atomic::store(_lock, 0);
return true;
}
private:
struct Node
{
T data;
};
private:
usize _capacityMask;
Node* _queue;
usize _capacity;
usize _head;
usize _tail;
mutable volatile int32 _lock;
};