-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspmc_queue.h
74 lines (60 loc) · 1.56 KB
/
spmc_queue.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
#pragma once
#include <atomic>
namespace zjwang
{
using ull = unsigned long long;
template<typename T, uint32_t CAPACITY = 1024>
class SPMCQueue
{
public:
SPMCQueue() {}
~SPMCQueue() {}
// 用了std::atomic, 起手就是一个disable copy and move
SPMCQueue(const SPMCQueue &) = delete;
SPMCQueue& operator = (const SPMCQueue &) = delete;
SPMCQueue(SPMCQueue &&) = delete;
SPMCQueue& operator = (SPMCQueue &&) = delete;
public:
struct Vistor
{
T *read() {
auto &block = q->mBlocks[(idx + 1) % CAPACITY];
ull newIdx = block.idx.load();
if (newIdx <= idx) {
return nullptr;
}
data = block.data;
if (block.idx.load() != newIdx) {
return nullptr;
}
idx = newIdx;
return &data;
}
SPMCQueue<T, CAPACITY> *q;
ull idx;
T data;
};
public:
Vistor getVistor() {
Vistor vistor;
vistor.q = this;
vistor.idx = mWriteIdx.load(std::memory_order_relaxed);
return vistor;
}
template<typename Writer>
void write(Writer write) {
auto &block = mBlocks[++mWriteIdx % CAPACITY];
write(block.data);
block.idx.store(mWriteIdx);
}
private:
friend class Vistor;
static constexpr uint32_t kCachelineSize = 64;
struct alignas(kCachelineSize) Block
{
std::atomic<ull> idx {0};
T data;
} mBlocks[CAPACITY];
alignas(kCachelineSize) std::atomic<ull> mWriteIdx;
};
} // zjwang