ractor_queue 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,677 @@
1
+ /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
2
+ #ifndef ATOMIC_QUEUE_ATOMIC_QUEUE_H_INCLUDED
3
+ #define ATOMIC_QUEUE_ATOMIC_QUEUE_H_INCLUDED
4
+
5
+ // Copyright (c) 2019 Maxim Egorushkin. MIT License. See the full licence in file LICENSE.
6
+
7
+ #include "defs.h"
8
+
9
+ #include <algorithm>
10
+ #include <cassert>
11
+ #include <cstddef>
12
+ #include <cstdint>
13
+ #include <memory>
14
+ #include <utility>
15
+
16
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
17
+
18
+ namespace atomic_queue {
19
+
20
+ using std::uint32_t;
21
+ using std::uint64_t;
22
+ using std::uint8_t;
23
+
24
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
25
+
26
+ namespace details {
27
+
28
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
29
+
30
+ template<size_t elements_per_cache_line> struct GetCacheLineIndexBits { static int constexpr value = 0; };
31
+ template<> struct GetCacheLineIndexBits<256> { static int constexpr value = 8; };
32
+ template<> struct GetCacheLineIndexBits<128> { static int constexpr value = 7; };
33
+ template<> struct GetCacheLineIndexBits< 64> { static int constexpr value = 6; };
34
+ template<> struct GetCacheLineIndexBits< 32> { static int constexpr value = 5; };
35
+ template<> struct GetCacheLineIndexBits< 16> { static int constexpr value = 4; };
36
+ template<> struct GetCacheLineIndexBits< 8> { static int constexpr value = 3; };
37
+ template<> struct GetCacheLineIndexBits< 4> { static int constexpr value = 2; };
38
+ template<> struct GetCacheLineIndexBits< 2> { static int constexpr value = 1; };
39
+
40
+ template<bool minimize_contention, unsigned array_size, size_t elements_per_cache_line>
41
+ struct GetIndexShuffleBits {
42
+ static int constexpr bits = GetCacheLineIndexBits<elements_per_cache_line>::value;
43
+ static unsigned constexpr min_size = 1u << (bits * 2);
44
+ static int constexpr value = array_size < min_size ? 0 : bits;
45
+ };
46
+
47
+ template<unsigned array_size, size_t elements_per_cache_line>
48
+ struct GetIndexShuffleBits<false, array_size, elements_per_cache_line> {
49
+ static int constexpr value = 0;
50
+ };
51
+
52
+ // Multiple writers/readers contend on the same cache line when storing/loading elements at
53
+ // subsequent indexes, aka false sharing. For power of 2 ring buffer size it is possible to re-map
54
+ // the index in such a way that each subsequent element resides on another cache line, which
55
+ // minimizes contention. This is done by swapping the lowest order N bits (which are the index of
56
+ // the element within the cache line) with the next N bits (which are the index of the cache line)
57
+ // of the element index.
58
+ template<int BITS>
59
+ ATOMIC_QUEUE_INLINE static constexpr unsigned remap_index(unsigned index) noexcept {
60
+ unsigned constexpr mix_mask{(1u << BITS) - 1};
61
+ unsigned const mix{(index ^ (index >> BITS)) & mix_mask};
62
+ return index ^ mix ^ (mix << BITS);
63
+ }
64
+
65
+ template<>
66
+ ATOMIC_QUEUE_INLINE constexpr unsigned remap_index<0>(unsigned index) noexcept {
67
+ return index;
68
+ }
69
+
70
+ template<int BITS, class T>
71
+ ATOMIC_QUEUE_INLINE static constexpr T& map(T* ATOMIC_QUEUE_RESTRICT elements, unsigned index) noexcept {
72
+ return elements[remap_index<BITS>(index)];
73
+ }
74
+
75
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
76
+
77
+ // Implement a "bit-twiddling hack" for finding the next power of 2 in either 32 bits or 64 bits
78
+ // in C++11 compatible constexpr functions. The library no longer maintains C++11 compatibility.
79
+
80
+ // "Runtime" version for 32 bits
81
+ // --a;
82
+ // a |= a >> 1;
83
+ // a |= a >> 2;
84
+ // a |= a >> 4;
85
+ // a |= a >> 8;
86
+ // a |= a >> 16;
87
+ // ++a;
88
+
89
+ template<class T>
90
+ ATOMIC_QUEUE_INLINE static constexpr T decrement(T x) noexcept {
91
+ return x - 1;
92
+ }
93
+
94
+ template<class T>
95
+ ATOMIC_QUEUE_INLINE static constexpr T increment(T x) noexcept {
96
+ return x + 1;
97
+ }
98
+
99
+ template<class T>
100
+ ATOMIC_QUEUE_INLINE static constexpr T or_equal(T x, unsigned u) noexcept {
101
+ return x | x >> u;
102
+ }
103
+
104
+ template<class T, class... Args>
105
+ ATOMIC_QUEUE_INLINE static constexpr T or_equal(T x, unsigned u, Args... rest) noexcept {
106
+ return or_equal(or_equal(x, u), rest...);
107
+ }
108
+
109
+ ATOMIC_QUEUE_INLINE static constexpr uint32_t round_up_to_power_of_2(uint32_t a) noexcept {
110
+ return increment(or_equal(decrement(a), 1, 2, 4, 8, 16));
111
+ }
112
+
113
+ ATOMIC_QUEUE_INLINE static constexpr uint64_t round_up_to_power_of_2(uint64_t a) noexcept {
114
+ return increment(or_equal(decrement(a), 1, 2, 4, 8, 16, 32));
115
+ }
116
+
117
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
118
+
119
+ template<class T>
120
+ constexpr T nil() noexcept {
121
+ #if __cpp_lib_atomic_is_always_lock_free // Better compile-time error message requires C++17.
122
+ static_assert(std::atomic<T>::is_always_lock_free, "Queue element type T is not atomic. Use AtomicQueue2/AtomicQueueB2 for such element types.");
123
+ #endif
124
+ return {};
125
+ }
126
+
127
+ template<class T>
128
+ ATOMIC_QUEUE_INLINE static void destroy_n(T* ATOMIC_QUEUE_RESTRICT p, unsigned n) noexcept {
129
+ for(auto q = p + n; p != q;)
130
+ (p++)->~T();
131
+ }
132
+
133
+ template<class T>
134
+ ATOMIC_QUEUE_INLINE static void swap_relaxed(std::atomic<T>& a, std::atomic<T>& b) noexcept {
135
+ auto a2 = a.load(X);
136
+ a.store(b.load(X), X);
137
+ b.store(a2, X);
138
+ }
139
+
140
+ template<class T>
141
+ ATOMIC_QUEUE_INLINE static void copy_relaxed(std::atomic<T>& a, std::atomic<T> const& b) noexcept {
142
+ a.store(b.load(X), X);
143
+ }
144
+
145
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
146
+
147
+ } // namespace details
148
+
149
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
150
+
151
+ template<class Derived>
152
+ class AtomicQueueCommon {
153
+ protected:
154
+ // Put these on different cache lines to avoid false sharing between readers and writers.
155
+ alignas(CACHE_LINE_SIZE) std::atomic<unsigned> head_ = {};
156
+ alignas(CACHE_LINE_SIZE) std::atomic<unsigned> tail_ = {};
157
+
158
+ // The special member functions are not thread-safe.
159
+
160
+ AtomicQueueCommon() noexcept = default;
161
+
162
+ AtomicQueueCommon(AtomicQueueCommon const& b) noexcept
163
+ : head_(b.head_.load(X))
164
+ , tail_(b.tail_.load(X)) {}
165
+
166
+ AtomicQueueCommon& operator=(AtomicQueueCommon const& b) noexcept {
167
+ details::copy_relaxed(head_, b.head_);
168
+ details::copy_relaxed(tail_, b.tail_);
169
+ return *this;
170
+ }
171
+
172
+ // Relatively semi-special swap is not thread-safe either.
173
+ void swap(AtomicQueueCommon& b) noexcept {
174
+ details::swap_relaxed(head_, b.head_);
175
+ details::swap_relaxed(tail_, b.tail_);
176
+ }
177
+
178
+ template<class T, T NIL>
179
+ ATOMIC_QUEUE_INLINE static T do_pop_atomic(std::atomic<T>& q_element) noexcept {
180
+ if(Derived::spsc_) {
181
+ for(;;) {
182
+ T element = q_element.load(A);
183
+ if(ATOMIC_QUEUE_LIKELY(element != NIL)) {
184
+ q_element.store(NIL, X);
185
+ return element;
186
+ }
187
+ if(Derived::maximize_throughput_)
188
+ spin_loop_pause();
189
+ }
190
+ }
191
+ else {
192
+ for(;;) {
193
+ T element = q_element.exchange(NIL, A); // (2) The store to wait for.
194
+ if(ATOMIC_QUEUE_LIKELY(element != NIL))
195
+ return element;
196
+ // Do speculative loads while busy-waiting to avoid broadcasting RFO messages.
197
+ do
198
+ spin_loop_pause();
199
+ while(Derived::maximize_throughput_ && q_element.load(X) == NIL);
200
+ }
201
+ }
202
+ }
203
+
204
+ template<class T, T NIL>
205
+ ATOMIC_QUEUE_INLINE static void do_push_atomic(T element, std::atomic<T>& q_element) noexcept {
206
+ assert(element != NIL);
207
+ if(Derived::spsc_) {
208
+ while(ATOMIC_QUEUE_UNLIKELY(q_element.load(X) != NIL))
209
+ if(Derived::maximize_throughput_)
210
+ spin_loop_pause();
211
+ q_element.store(element, R);
212
+ }
213
+ else {
214
+ for(T expected = NIL; ATOMIC_QUEUE_UNLIKELY(!q_element.compare_exchange_weak(expected, element, R, X)); expected = NIL) {
215
+ do
216
+ spin_loop_pause(); // (1) Wait for store (2) to complete.
217
+ while(Derived::maximize_throughput_ && q_element.load(X) != NIL);
218
+ }
219
+ }
220
+ }
221
+
222
+ enum State : unsigned char { EMPTY, STORING, STORED, LOADING };
223
+
224
+ template<class T>
225
+ ATOMIC_QUEUE_INLINE static T do_pop_any(std::atomic<unsigned char>& state, T& q_element) noexcept {
226
+ if(Derived::spsc_) {
227
+ while(ATOMIC_QUEUE_UNLIKELY(state.load(A) != STORED))
228
+ if(Derived::maximize_throughput_)
229
+ spin_loop_pause();
230
+ T element{std::move(q_element)};
231
+ state.store(EMPTY, R);
232
+ return element;
233
+ }
234
+ else {
235
+ for(;;) {
236
+ unsigned char expected = STORED;
237
+ if(ATOMIC_QUEUE_LIKELY(state.compare_exchange_weak(expected, LOADING, A, X))) {
238
+ T element{std::move(q_element)};
239
+ state.store(EMPTY, R);
240
+ return element;
241
+ }
242
+ // Do speculative loads while busy-waiting to avoid broadcasting RFO messages.
243
+ do
244
+ spin_loop_pause();
245
+ while(Derived::maximize_throughput_ && state.load(X) != STORED);
246
+ }
247
+ }
248
+ }
249
+
250
+ template<class U, class T>
251
+ ATOMIC_QUEUE_INLINE static void do_push_any(U&& element, std::atomic<unsigned char>& state, T& q_element) noexcept {
252
+ if(Derived::spsc_) {
253
+ while(ATOMIC_QUEUE_UNLIKELY(state.load(A) != EMPTY))
254
+ if(Derived::maximize_throughput_)
255
+ spin_loop_pause();
256
+ q_element = std::forward<U>(element);
257
+ state.store(STORED, R);
258
+ }
259
+ else {
260
+ for(;;) {
261
+ unsigned char expected = EMPTY;
262
+ if(ATOMIC_QUEUE_LIKELY(state.compare_exchange_weak(expected, STORING, A, X))) {
263
+ q_element = std::forward<U>(element);
264
+ state.store(STORED, R);
265
+ return;
266
+ }
267
+ // Do speculative loads while busy-waiting to avoid broadcasting RFO messages.
268
+ do
269
+ spin_loop_pause();
270
+ while(Derived::maximize_throughput_ && state.load(X) != EMPTY);
271
+ }
272
+ }
273
+ }
274
+
275
+ public:
276
+ template<class T>
277
+ ATOMIC_QUEUE_INLINE bool try_push(T&& element) noexcept {
278
+ auto head = head_.load(X);
279
+ if(Derived::spsc_) {
280
+ if(static_cast<int>(head - tail_.load(X)) >= static_cast<int>(static_cast<Derived&>(*this).size_))
281
+ return false;
282
+ head_.store(head + 1, X);
283
+ }
284
+ else {
285
+ do {
286
+ if(static_cast<int>(head - tail_.load(X)) >= static_cast<int>(static_cast<Derived&>(*this).size_))
287
+ return false;
288
+ } while(ATOMIC_QUEUE_UNLIKELY(!head_.compare_exchange_weak(head, head + 1, X, X))); // This loop is not FIFO.
289
+ }
290
+
291
+ static_cast<Derived&>(*this).do_push(std::forward<T>(element), head);
292
+ return true;
293
+ }
294
+
295
+ template<class T>
296
+ ATOMIC_QUEUE_INLINE bool try_pop(T& element) noexcept {
297
+ auto tail = tail_.load(X);
298
+ if(Derived::spsc_) {
299
+ if(static_cast<int>(head_.load(X) - tail) <= 0)
300
+ return false;
301
+ tail_.store(tail + 1, X);
302
+ }
303
+ else {
304
+ do {
305
+ if(static_cast<int>(head_.load(X) - tail) <= 0)
306
+ return false;
307
+ } while(ATOMIC_QUEUE_UNLIKELY(!tail_.compare_exchange_weak(tail, tail + 1, X, X))); // This loop is not FIFO.
308
+ }
309
+
310
+ element = static_cast<Derived&>(*this).do_pop(tail);
311
+ return true;
312
+ }
313
+
314
+ template<class T>
315
+ ATOMIC_QUEUE_INLINE void push(T&& element) noexcept {
316
+ unsigned head;
317
+ if(Derived::spsc_) {
318
+ head = head_.load(X);
319
+ head_.store(head + 1, X);
320
+ }
321
+ else {
322
+ constexpr auto memory_order = Derived::total_order_ ? std::memory_order_seq_cst : std::memory_order_relaxed;
323
+ head = head_.fetch_add(1, memory_order); // FIFO and total order on Intel regardless, as of 2019.
324
+ }
325
+ static_cast<Derived&>(*this).do_push(std::forward<T>(element), head);
326
+ }
327
+
328
+ ATOMIC_QUEUE_INLINE auto pop() noexcept {
329
+ unsigned tail;
330
+ if(Derived::spsc_) {
331
+ tail = tail_.load(X);
332
+ tail_.store(tail + 1, X);
333
+ }
334
+ else {
335
+ constexpr auto memory_order = Derived::total_order_ ? std::memory_order_seq_cst : std::memory_order_relaxed;
336
+ tail = tail_.fetch_add(1, memory_order); // FIFO and total order on Intel regardless, as of 2019.
337
+ }
338
+ return static_cast<Derived&>(*this).do_pop(tail);
339
+ }
340
+
341
+ ATOMIC_QUEUE_INLINE bool was_empty() const noexcept {
342
+ return !was_size();
343
+ }
344
+
345
+ ATOMIC_QUEUE_INLINE bool was_full() const noexcept {
346
+ return was_size() >= capacity();
347
+ }
348
+
349
+ ATOMIC_QUEUE_INLINE unsigned was_size() const noexcept {
350
+ // tail_ can be greater than head_ because of consumers doing pop, rather that try_pop, when the queue is empty.
351
+ unsigned n{head_.load(X) - tail_.load(X)};
352
+ return static_cast<int>(n) < 0 ? 0 : n; // Windows headers break std::min/max by default. Do std::max<int>(n, 0) the hard way here.
353
+ }
354
+
355
+ ATOMIC_QUEUE_INLINE unsigned capacity() const noexcept {
356
+ return static_cast<Derived const&>(*this).size_;
357
+ }
358
+ };
359
+
360
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
361
+
362
+ template<class T, unsigned SIZE, T NIL = details::nil<T>(), bool MINIMIZE_CONTENTION = true, bool MAXIMIZE_THROUGHPUT = true, bool TOTAL_ORDER = false, bool SPSC = false>
363
+ class AtomicQueue : public AtomicQueueCommon<AtomicQueue<T, SIZE, NIL, MINIMIZE_CONTENTION, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>> {
364
+ using Base = AtomicQueueCommon<AtomicQueue<T, SIZE, NIL, MINIMIZE_CONTENTION, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>>;
365
+ friend Base;
366
+
367
+ static constexpr unsigned size_ = MINIMIZE_CONTENTION ? details::round_up_to_power_of_2(SIZE) : SIZE;
368
+ static constexpr int SHUFFLE_BITS = details::GetIndexShuffleBits<MINIMIZE_CONTENTION, size_, CACHE_LINE_SIZE / sizeof(std::atomic<T>)>::value;
369
+ static constexpr bool total_order_ = TOTAL_ORDER;
370
+ static constexpr bool spsc_ = SPSC;
371
+ static constexpr bool maximize_throughput_ = MAXIMIZE_THROUGHPUT;
372
+
373
+ alignas(CACHE_LINE_SIZE) std::atomic<T> elements_[size_];
374
+
375
+ ATOMIC_QUEUE_INLINE T do_pop(unsigned tail) noexcept {
376
+ std::atomic<T>& q_element = details::map<SHUFFLE_BITS>(elements_, tail % size_);
377
+ return Base::template do_pop_atomic<T, NIL>(q_element);
378
+ }
379
+
380
+ ATOMIC_QUEUE_INLINE void do_push(T element, unsigned head) noexcept {
381
+ std::atomic<T>& q_element = details::map<SHUFFLE_BITS>(elements_, head % size_);
382
+ Base::template do_push_atomic<T, NIL>(element, q_element);
383
+ }
384
+
385
+ public:
386
+ using value_type = T;
387
+
388
+ AtomicQueue() noexcept {
389
+ assert(std::atomic<T>{NIL}.is_lock_free()); // Queue element type T is not atomic. Use AtomicQueue2/AtomicQueueB2 for such element types.
390
+ for(auto p = elements_, q = elements_ + size_; p != q; ++p)
391
+ p->store(NIL, X);
392
+ }
393
+
394
+ AtomicQueue(AtomicQueue const&) = delete;
395
+ AtomicQueue& operator=(AtomicQueue const&) = delete;
396
+ };
397
+
398
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
399
+
400
+ template<class T, unsigned SIZE, bool MINIMIZE_CONTENTION = true, bool MAXIMIZE_THROUGHPUT = true, bool TOTAL_ORDER = false, bool SPSC = false>
401
+ class AtomicQueue2 : public AtomicQueueCommon<AtomicQueue2<T, SIZE, MINIMIZE_CONTENTION, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>> {
402
+ using Base = AtomicQueueCommon<AtomicQueue2<T, SIZE, MINIMIZE_CONTENTION, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>>;
403
+ using State = typename Base::State;
404
+ friend Base;
405
+
406
+ static constexpr unsigned size_ = MINIMIZE_CONTENTION ? details::round_up_to_power_of_2(SIZE) : SIZE;
407
+ static constexpr int SHUFFLE_BITS = details::GetIndexShuffleBits<MINIMIZE_CONTENTION, size_, CACHE_LINE_SIZE / sizeof(State)>::value;
408
+ static constexpr bool total_order_ = TOTAL_ORDER;
409
+ static constexpr bool spsc_ = SPSC;
410
+ static constexpr bool maximize_throughput_ = MAXIMIZE_THROUGHPUT;
411
+
412
+ alignas(CACHE_LINE_SIZE) std::atomic<unsigned char> states_[size_] = {};
413
+ alignas(CACHE_LINE_SIZE) T elements_[size_] = {};
414
+
415
+ ATOMIC_QUEUE_INLINE T do_pop(unsigned tail) noexcept {
416
+ unsigned index = details::remap_index<SHUFFLE_BITS>(tail % size_);
417
+ return Base::do_pop_any(states_[index], elements_[index]);
418
+ }
419
+
420
+ template<class U>
421
+ ATOMIC_QUEUE_INLINE void do_push(U&& element, unsigned head) noexcept {
422
+ unsigned index = details::remap_index<SHUFFLE_BITS>(head % size_);
423
+ Base::do_push_any(std::forward<U>(element), states_[index], elements_[index]);
424
+ }
425
+
426
+ public:
427
+ using value_type = T;
428
+
429
+ AtomicQueue2() noexcept = default;
430
+ AtomicQueue2(AtomicQueue2 const&) = delete;
431
+ AtomicQueue2& operator=(AtomicQueue2 const&) = delete;
432
+ };
433
+
434
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
435
+
436
+ template<class T, class A = std::allocator<T>, T NIL = details::nil<T>(), bool MAXIMIZE_THROUGHPUT = true, bool TOTAL_ORDER = false, bool SPSC = false>
437
+ class AtomicQueueB : private std::allocator_traits<A>::template rebind_alloc<std::atomic<T>>,
438
+ public AtomicQueueCommon<AtomicQueueB<T, A, NIL, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>> {
439
+ using AllocatorElements = typename std::allocator_traits<A>::template rebind_alloc<std::atomic<T>>;
440
+ using Base = AtomicQueueCommon<AtomicQueueB<T, A, NIL, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>>;
441
+ friend Base;
442
+
443
+ static constexpr bool total_order_ = TOTAL_ORDER;
444
+ static constexpr bool spsc_ = SPSC;
445
+ static constexpr bool maximize_throughput_ = MAXIMIZE_THROUGHPUT;
446
+
447
+ static constexpr auto ELEMENTS_PER_CACHE_LINE = CACHE_LINE_SIZE / sizeof(std::atomic<T>);
448
+ static_assert(ELEMENTS_PER_CACHE_LINE, "Unexpected ELEMENTS_PER_CACHE_LINE.");
449
+
450
+ static constexpr auto SHUFFLE_BITS = details::GetCacheLineIndexBits<ELEMENTS_PER_CACHE_LINE>::value;
451
+ static_assert(SHUFFLE_BITS, "Unexpected SHUFFLE_BITS.");
452
+
453
+ // AtomicQueueCommon members are stored into by readers and writers.
454
+ // Allocate these immutable members on another cache line which never gets invalidated by stores.
455
+ alignas(CACHE_LINE_SIZE)
456
+ unsigned size_;
457
+
458
+ // The C++ strict aliasing rules assume that pointers to the same decayed type may alias.
459
+ // The C++ strict aliasing rules assume that pointers to any char type may alias anything and everything.
460
+ // A dynamically allocated array may not alias anything else by construction.
461
+ // Explicitly annotate the circular buffer array pointer as not aliasing anything else with restrict keyword.
462
+ std::atomic<T>* ATOMIC_QUEUE_RESTRICT elements_;
463
+
464
+ ATOMIC_QUEUE_INLINE T do_pop(unsigned tail) noexcept {
465
+ std::atomic<T>& q_element = details::map<SHUFFLE_BITS>(elements_, tail & (size_ - 1));
466
+ return Base::template do_pop_atomic<T, NIL>(q_element);
467
+ }
468
+
469
+ ATOMIC_QUEUE_INLINE void do_push(T element, unsigned head) noexcept {
470
+ std::atomic<T>& q_element = details::map<SHUFFLE_BITS>(elements_, head & (size_ - 1));
471
+ Base::template do_push_atomic<T, NIL>(element, q_element);
472
+ }
473
+
474
+ public:
475
+ using value_type = T;
476
+ using allocator_type = A;
477
+
478
+ // The special member functions are not thread-safe.
479
+
480
+ AtomicQueueB(unsigned size, A const& allocator = A{})
481
+ : AllocatorElements(allocator)
482
+ , size_(std::max(details::round_up_to_power_of_2(size), 1u << (SHUFFLE_BITS * 2)))
483
+ , elements_(AllocatorElements::allocate(size_)) {
484
+ assert(std::atomic<T>{NIL}.is_lock_free()); // Queue element type T is not atomic. Use AtomicQueue2/AtomicQueueB2 for such element types.
485
+ std::uninitialized_fill_n(elements_, size_, NIL);
486
+ assert(get_allocator() == allocator); // The standard requires the original and rebound allocators to manage the same state.
487
+ }
488
+
489
+ AtomicQueueB(AtomicQueueB&& b) noexcept
490
+ : AllocatorElements(static_cast<AllocatorElements&&>(b)) // TODO: This must be noexcept, static_assert that.
491
+ , Base(static_cast<Base&&>(b))
492
+ , size_(std::exchange(b.size_, 0))
493
+ , elements_(std::exchange(b.elements_, nullptr))
494
+ {}
495
+
496
+ AtomicQueueB& operator=(AtomicQueueB&& b) noexcept {
497
+ b.swap(*this);
498
+ return *this;
499
+ }
500
+
501
+ ~AtomicQueueB() noexcept {
502
+ if(elements_) {
503
+ details::destroy_n(elements_, size_);
504
+ AllocatorElements::deallocate(elements_, size_); // TODO: This must be noexcept, static_assert that.
505
+ }
506
+ }
507
+
508
+ A get_allocator() const noexcept {
509
+ return *this; // The standard requires implicit conversion between rebound allocators.
510
+ }
511
+
512
+ void swap(AtomicQueueB& b) noexcept {
513
+ using std::swap;
514
+ swap(static_cast<AllocatorElements&>(*this), static_cast<AllocatorElements&>(b));
515
+ Base::swap(b);
516
+ swap(size_, b.size_);
517
+ swap(elements_, b.elements_);
518
+ }
519
+
520
+ friend void swap(AtomicQueueB& a, AtomicQueueB& b) noexcept {
521
+ a.swap(b);
522
+ }
523
+ };
524
+
525
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
526
+
527
+ template<class T, class A = std::allocator<T>, bool MAXIMIZE_THROUGHPUT = true, bool TOTAL_ORDER = false, bool SPSC = false>
528
+ class AtomicQueueB2 : private std::allocator_traits<A>::template rebind_alloc<unsigned char>,
529
+ public AtomicQueueCommon<AtomicQueueB2<T, A, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>> {
530
+ using StorageAllocator = typename std::allocator_traits<A>::template rebind_alloc<unsigned char>;
531
+ using Base = AtomicQueueCommon<AtomicQueueB2<T, A, MAXIMIZE_THROUGHPUT, TOTAL_ORDER, SPSC>>;
532
+ using State = typename Base::State;
533
+ using AtomicState = std::atomic<unsigned char>;
534
+ friend Base;
535
+
536
+ static constexpr bool total_order_ = TOTAL_ORDER;
537
+ static constexpr bool spsc_ = SPSC;
538
+ static constexpr bool maximize_throughput_ = MAXIMIZE_THROUGHPUT;
539
+
540
+ // AtomicQueueCommon members are stored into by readers and writers.
541
+ // Allocate these immutable members on another cache line which never gets invalidated by stores.
542
+ alignas(CACHE_LINE_SIZE)
543
+ unsigned size_;
544
+
545
+ // The C++ strict aliasing rules assume that pointers to the same decayed type may alias.
546
+ // The C++ strict aliasing rules assume that pointers to any char type may alias anything and everything.
547
+ // A dynamically allocated array may not alias anything else by construction.
548
+ // Explicitly annotate the circular buffer array pointers as not aliasing anything else with restrict keyword.
549
+ AtomicState* ATOMIC_QUEUE_RESTRICT states_;
550
+ T* ATOMIC_QUEUE_RESTRICT elements_;
551
+
552
+ static constexpr auto STATES_PER_CACHE_LINE = CACHE_LINE_SIZE / sizeof(AtomicState);
553
+ static_assert(STATES_PER_CACHE_LINE, "Unexpected STATES_PER_CACHE_LINE.");
554
+
555
+ static constexpr auto SHUFFLE_BITS = details::GetCacheLineIndexBits<STATES_PER_CACHE_LINE>::value;
556
+ static_assert(SHUFFLE_BITS, "Unexpected SHUFFLE_BITS.");
557
+
558
+ ATOMIC_QUEUE_INLINE T do_pop(unsigned tail) noexcept {
559
+ unsigned index = details::remap_index<SHUFFLE_BITS>(tail & (size_ - 1));
560
+ return Base::do_pop_any(states_[index], elements_[index]);
561
+ }
562
+
563
+ template<class U>
564
+ ATOMIC_QUEUE_INLINE void do_push(U&& element, unsigned head) noexcept {
565
+ unsigned index = details::remap_index<SHUFFLE_BITS>(head & (size_ - 1));
566
+ Base::do_push_any(std::forward<U>(element), states_[index], elements_[index]);
567
+ }
568
+
569
+ template<class U>
570
+ U* allocate_() {
571
+ U* p = reinterpret_cast<U*>(StorageAllocator::allocate(size_ * sizeof(U)));
572
+ assert(reinterpret_cast<uintptr_t>(p) % alignof(U) == 0); // Allocated storage must be suitably aligned for U.
573
+ return p;
574
+ }
575
+
576
+ template<class U>
577
+ void deallocate_(U* p) noexcept {
578
+ StorageAllocator::deallocate(reinterpret_cast<unsigned char*>(p), size_ * sizeof(U)); // TODO: This must be noexcept, static_assert that.
579
+ }
580
+
581
+ public:
582
+ using value_type = T;
583
+ using allocator_type = A;
584
+
585
+ // The special member functions are not thread-safe.
586
+
587
+ AtomicQueueB2(unsigned size, A const& allocator = A{})
588
+ : StorageAllocator(allocator)
589
+ , size_(std::max(details::round_up_to_power_of_2(size), 1u << (SHUFFLE_BITS * 2)))
590
+ , states_(allocate_<AtomicState>())
591
+ , elements_(allocate_<T>()) {
592
+ std::uninitialized_fill_n(states_, size_, Base::EMPTY);
593
+ A a = get_allocator();
594
+ assert(a == allocator); // The standard requires the original and rebound allocators to manage the same state.
595
+ for(auto p = elements_, q = elements_ + size_; p < q; ++p)
596
+ std::allocator_traits<A>::construct(a, p);
597
+ }
598
+
599
+ AtomicQueueB2(AtomicQueueB2&& b) noexcept
600
+ : StorageAllocator(static_cast<StorageAllocator&&>(b)) // TODO: This must be noexcept, static_assert that.
601
+ , Base(static_cast<Base&&>(b))
602
+ , size_(std::exchange(b.size_, 0))
603
+ , states_(std::exchange(b.states_, nullptr))
604
+ , elements_(std::exchange(b.elements_, nullptr))
605
+ {}
606
+
607
+ AtomicQueueB2& operator=(AtomicQueueB2&& b) noexcept {
608
+ b.swap(*this);
609
+ return *this;
610
+ }
611
+
612
+ ~AtomicQueueB2() noexcept {
613
+ if(elements_) {
614
+ A a = get_allocator();
615
+ for(auto p = elements_, q = elements_ + size_; p < q; ++p)
616
+ std::allocator_traits<A>::destroy(a, p);
617
+ deallocate_(elements_);
618
+ details::destroy_n(states_, size_);
619
+ deallocate_(states_);
620
+ }
621
+ }
622
+
623
+ A get_allocator() const noexcept {
624
+ return *this; // The standard requires implicit conversion between rebound allocators.
625
+ }
626
+
627
+ void swap(AtomicQueueB2& b) noexcept {
628
+ using std::swap;
629
+ swap(static_cast<StorageAllocator&>(*this), static_cast<StorageAllocator&>(b));
630
+ Base::swap(b);
631
+ swap(size_, b.size_);
632
+ swap(states_, b.states_);
633
+ swap(elements_, b.elements_);
634
+ }
635
+
636
+ friend void swap(AtomicQueueB2& a, AtomicQueueB2& b) noexcept {
637
+ a.swap(b);
638
+ }
639
+ };
640
+
641
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
642
+
643
+ template<class Queue>
644
+ struct RetryDecorator : Queue {
645
+ using T = typename Queue::value_type;
646
+
647
+ using Queue::Queue;
648
+
649
+ ATOMIC_QUEUE_INLINE void push(T element) noexcept {
650
+ while(!this->try_push(element))
651
+ spin_loop_pause();
652
+ }
653
+
654
+ ATOMIC_QUEUE_INLINE T pop() noexcept {
655
+ T element;
656
+ while(!this->try_pop(element))
657
+ spin_loop_pause();
658
+ return element;
659
+ }
660
+ };
661
+
662
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
663
+
664
+ template<class Queue, size_t Capacity>
665
+ struct CapacityArgAdaptor : Queue {
666
+ CapacityArgAdaptor()
667
+ : Queue(Capacity)
668
+ {}
669
+ };
670
+
671
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
672
+
673
+ } // namespace atomic_queue
674
+
675
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
676
+
677
+ #endif // ATOMIC_QUEUE_ATOMIC_QUEUE_H_INCLUDED