COROIO: coroio/grow_mailbox.hpp Source File
COROIO
Loading...
Searching...
No Matches
grow_mailbox.hpp
1#pragma once
2
3#include <algorithm>
4#include <atomic>
5#include <bit>
6#include <cassert>
7#include <cstddef>
8#include <cstdint>
9#include <new>
10#include <optional>
11#include <stdexcept>
12#include <type_traits>
13#include <utility>
14
15namespace NNet {
16
17namespace NDetail {
18
19inline constexpr size_t MailboxCacheLine = 64;
20
32template<typename T>
33class TMpscRing {
34public:
35 static constexpr uint64_t ClosedBit = uint64_t(1) << 63;
36
37 enum class EPush {
38 Ok,
39 Full,
40 Closed,
41 };
42
44 explicit TMpscRing(size_t capacity)
45 : Mask_(capacity - 1)
46 , Cells_(new TCell[capacity])
47 {
48 assert(capacity >= 2 && (capacity & Mask_) == 0);
49 for (size_t i = 0; i < capacity; ++i) {
50 Cells_[i].Seq.store(i, std::memory_order_relaxed);
51 }
52 }
53
56 const uint64_t tail = Tail_.load(std::memory_order_relaxed) & ~ClosedBit;
57 for (uint64_t pos = Head_; pos != tail; ++pos) {
58 Value(Cells_[pos & Mask_])->~T();
59 }
60 delete[] Cells_;
61 }
62
63 TMpscRing(const TMpscRing&) = delete;
64 TMpscRing& operator=(const TMpscRing&) = delete;
65
67 EPush TryPush(T& value) {
68 uint64_t pos = Tail_.load(std::memory_order_relaxed);
69 TCell* cell = nullptr;
70 while (true) {
71 if (pos & ClosedBit) {
72 return EPush::Closed;
73 }
74 cell = &Cells_[pos & Mask_];
75 // Acquire: the consumer has moved the previous value out before it freed the cell
76 const int64_t diff = static_cast<int64_t>(cell->Seq.load(std::memory_order_acquire) - pos);
77 if (diff == 0) {
78 // Relaxed: the tail only hands out positions, the cell number orders the data
79 if (Tail_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed, std::memory_order_relaxed)) {
80 break;
81 }
82 } else if (diff < 0) {
83 return EPush::Full;
84 } else {
85 pos = Tail_.load(std::memory_order_relaxed);
86 }
87 }
88 new (cell->Storage) T(std::move(value));
89 cell->Seq.store(pos + 1, std::memory_order_release);
90 return EPush::Ok;
91 }
92
94 std::optional<T> TryPop() {
95 TCell& cell = Cells_[Head_ & Mask_];
96 if (cell.Seq.load(std::memory_order_acquire) != Head_ + 1) {
97 return std::nullopt;
98 }
99 T* value = Value(cell);
100 std::optional<T> result(std::move(*value));
101 value->~T();
102 // Free for the position one lap ahead
103 cell.Seq.store(Head_ + Mask_ + 1, std::memory_order_release);
104 ++Head_;
105 return result;
106 }
107
109 void Close() {
110 Tail_.fetch_or(ClosedBit, std::memory_order_acq_rel);
111 }
112
114 bool Finished() const {
115 const uint64_t tail = Tail_.load(std::memory_order_acquire);
116 return (tail & ClosedBit) && Head_ == (tail & ~ClosedBit);
117 }
118
119 size_t Capacity() const {
120 return Mask_ + 1;
121 }
122
123private:
124 // A value and its number in one line, so producers of neighbouring cells do not share lines
125 struct alignas(MailboxCacheLine) TCell {
126 std::atomic<uint64_t> Seq;
127 alignas(T) std::byte Storage[sizeof(T)];
128 };
129
130 static T* Value(TCell& cell) {
131 return std::launder(reinterpret_cast<T*>(cell.Storage));
132 }
133
134 const uint64_t Mask_;
135 TCell* const Cells_;
136 alignas(MailboxCacheLine) std::atomic<uint64_t> Tail_ = 0;
137 alignas(MailboxCacheLine) uint64_t Head_ = 0;
138};
139
140} // namespace NDetail
141
188template<typename T, size_t Levels = 32>
190 static_assert(std::is_nothrow_move_constructible_v<T>,
191 "a producer must not leave a claimed cell unwritten");
192
193 using TRing = NDetail::TMpscRing<T>;
194
195public:
197 explicit TGrowMailbox(size_t initialCapacity = 64)
198 : Initial_(std::bit_ceil(std::max<size_t>(initialCapacity, 2)))
199 , Consuming_(new TRing(Initial_))
200 {
201 Rings_[0].store(Consuming_, std::memory_order_relaxed);
202 }
203
204 ~TGrowMailbox() {
205 for (auto& ring : Rings_) {
206 delete ring.load(std::memory_order_relaxed);
207 }
208 }
209
210 TGrowMailbox(const TGrowMailbox&) = delete;
211 TGrowMailbox& operator=(const TGrowMailbox&) = delete;
212
219 void Push(T&& value) {
220 while (true) {
221 // Acquire pairs with the CAS in Grow: the ring of a level is set before the level opens
222 const uint32_t open = Open_.load(std::memory_order_acquire);
223 TRing* ring = Rings_[open].load(std::memory_order_acquire);
224 const auto result = ring->TryPush(value);
225 if (result == TRing::EPush::Ok) {
226 return;
227 }
228 if (result == TRing::EPush::Full) {
229 ring->Close();
230 }
231 Grow(open);
232 }
233 }
234
236 std::optional<T> Pop() {
237 while (true) {
238 if (auto value = Consuming_->TryPop()) {
239 return value;
240 }
241 // A level opens only after the ring below it is closed
242 if (Open_.load(std::memory_order_acquire) <= Current_ || !Consuming_->Finished()) {
243 return std::nullopt;
244 }
245 ++Current_;
246 Consuming_ = Rings_[Current_].load(std::memory_order_acquire);
247 }
248 }
249
251 size_t Capacity() const {
252 return Initial_ << Open_.load(std::memory_order_relaxed);
253 }
254
255private:
256 // Any producer that saw the ring of `open` closed helps to open the next level
257 void Grow(uint32_t open) {
258 if (open + 1 == Levels) {
259 throw std::length_error("TGrowMailbox: all levels are used");
260 }
261 if (!Rings_[open + 1].load(std::memory_order_acquire)) {
262 auto* fresh = new TRing(Initial_ << (open + 1));
263 TRing* expected = nullptr;
264 if (!Rings_[open + 1].compare_exchange_strong(expected, fresh,
265 std::memory_order_acq_rel, std::memory_order_acquire))
266 {
267 delete fresh;
268 }
269 }
270 uint32_t expected = open;
271 Open_.compare_exchange_strong(expected, open + 1, std::memory_order_acq_rel, std::memory_order_relaxed);
272 }
273
274 const size_t Initial_;
275 // Read by every push, changed once per level
276 alignas(NDetail::MailboxCacheLine) std::atomic<uint32_t> Open_ = 0;
277 std::atomic<TRing*> Rings_[Levels];
278 // Consumer only
279 alignas(NDetail::MailboxCacheLine) uint32_t Current_ = 0;
280 TRing* Consuming_;
281};
282
283} // namespace NNet
Bounded ring with many producers and one consumer; a level of TGrowMailbox.
Definition grow_mailbox.hpp:33
TMpscRing(size_t capacity)
capacity is a power of two, at least 2: with one cell "written" and "free" look the same.
Definition grow_mailbox.hpp:44
EPush TryPush(T &value)
Any thread. Moves from value only on Ok.
Definition grow_mailbox.hpp:67
std::optional< T > TryPop()
Consumer only. Empty also while the cell at the head is claimed and not written yet.
Definition grow_mailbox.hpp:94
void Close()
Any thread.
Definition grow_mailbox.hpp:109
~TMpscRing()
Destroys the values that were not popped. The producers have stopped.
Definition grow_mailbox.hpp:55
bool Finished() const
Consumer only: closed, and every value pushed before has been popped.
Definition grow_mailbox.hpp:114
Unbounded lock-free queue with many producers and one consumer, without links.
Definition grow_mailbox.hpp:189
std::optional< T > Pop()
Removes the oldest value, or returns nothing if there is none. Consumer only.
Definition grow_mailbox.hpp:236
void Push(T &&value)
Appends a value. Any thread.
Definition grow_mailbox.hpp:219
TGrowMailbox(size_t initialCapacity=64)
initialCapacity is the size of the first ring, rounded up to a power of two, at least 2.
Definition grow_mailbox.hpp:197
size_t Capacity() const
Capacity of the ring that producers push to now. Any thread; for diagnostics and tests.
Definition grow_mailbox.hpp:251