-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPSCLockFreeQueue.h
More file actions
87 lines (66 loc) · 2.4 KB
/
SPSCLockFreeQueue.h
File metadata and controls
87 lines (66 loc) · 2.4 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
#pragma once
#include <array>
#include <cstdint>
#include <atomic>
#include <optional>
namespace JacobVW {
// use 128 to cover all cases - x86 is usually 64 and apple 128
constexpr std::size_t hardware_destructive_interference_size = 128;
template <typename T, std::size_t SIZE>
class SPSCLockFreeQueue {
public:
bool Push(T&& value)
{
auto currentHead = m_head.load(std::memory_order_relaxed);
auto nextHead = (currentHead + 1) % SIZE;
if (nextHead == m_tail.load(std::memory_order_acquire)) {
// full
return false;
}
m_buffer[currentHead] = std::move(value);
m_head.store(nextHead, std::memory_order_release);
return true;
}
bool Push(const T& value)
{
const auto currentHead = m_head.load(std::memory_order_relaxed);
const auto nextHead = (currentHead + 1) % SIZE;
if (nextHead == m_tail.load(std::memory_order_acquire)) {
return false;
}
m_buffer[currentHead] = value;
m_head.store(nextHead, std::memory_order_release);
return true;
}
std::optional<T> Pop() {
auto currentTail = m_tail.load(std::memory_order_relaxed);
// empty
if (currentTail == m_head.load(std::memory_order_acquire))
{
return std::nullopt;
}
std::optional<T> item(std::move(m_buffer[currentTail]));
auto nextTail = (currentTail + 1) % SIZE;
m_tail.store(nextTail, std::memory_order_release);
return item;
}
bool IsEmpty() const
{
return m_head.load(std::memory_order_acquire) ==
m_tail.load(std::memory_order_acquire);
}
bool IsFull() const
{
return (m_head.load(std::memory_order_acquire) + 1) % SIZE ==
m_tail.load(std::memory_order_acquire);
}
constexpr std::size_t Capacity() const
{
return SIZE - 1;
}
private:
alignas(hardware_destructive_interference_size) std::array<T, SIZE> m_buffer {};
alignas(hardware_destructive_interference_size) std::atomic<uint64_t> m_head {};
alignas(hardware_destructive_interference_size) std::atomic<uint64_t> m_tail {};
};
}