Debian Codegraph @

src/dmlc-core/include/dmlc/concurrentqueue.h

raw symbols SCIP
1 //! \cond Doxygen_Suppress
2 // Provides a C++11 implementation of a multi-producer, multi-consumer lock-free queue.
3 // An overview, including benchmark results, is provided here:
4 // http://moodycamel.com/blog/2014/a-fast-general-purpose-lock-free-queue-for-c++
5 // The full design is also described in excruciating detail at:
6 // http://moodycamel.com/blog/2014/detailed-design-of-a-lock-free-queue
7
8 // Simplified BSD license:
9 // Copyright (c) 2013-2016, Cameron Desrochers.
10 // All rights reserved.
11 //
12 // Redistribution and use in source and binary forms, with or without modification,
13 // are permitted provided that the following conditions are met:
14 //
15 // - Redistributions of source code must retain the above copyright notice, this list of
16 // conditions and the following disclaimer.
17 // - Redistributions in binary form must reproduce the above copyright notice, this list of
18 // conditions and the following disclaimer in the documentation and/or other materials
19 // provided with the distribution.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
22 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
24 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26 // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
28 // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
29 // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #ifndef DMLC_CONCURRENTQUEUE_H_
31 #define DMLC_CONCURRENTQUEUE_H_
32 #pragma once
33
34 #if defined(__GNUC__)
35 // Disable -Wconversion warnings (spuriously triggered when Traits::size_t and
36 // Traits::index_t are set to < 32 bits, causing integer promotion, causing warnings
37 // upon assigning any computed values)
38
39
40
41 #ifdef MCDBGQ_USE_RELACY
42
43 #endif
44 #endif
45
46 #if defined(_WIN32) || defined(__WINDOWS__) || defined(__WIN32__) || defined(_WIN64)
47 #define NOMINMAX
48 #include <windows.h> // for GetCurrentThreadId()
49 #endif
50
51 #if defined(__APPLE__)
52 #include "TargetConditionals.h"
53 #endif
54
55 #ifdef MCDBGQ_USE_RELACY
56 #include "relacy/relacy_std.hpp"
57 #include "relacy_shims.h"
58 // We only use malloc/free anyway, and the delete macro messes up `= delete` method
59 // declarations. We'll override the default trait malloc ourselves without a macro.
60 #undef new
61 #undef delete
62 #undef malloc
63 #undef free
64 #else
65 #include <atomic> // Requires C++11. Sorry VS2010.
66 #include <cassert>
67 #endif
68 #include <algorithm>
69 #include <array>
70 #include <climits> // for CHAR_BIT
71 #include <cstddef> // for max_align_t
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <thread> // partly for __WINPTHREADS_VERSION if on MinGW-w64 w/ POSIX threading
76 #include <type_traits>
77 #include <utility>
78
79 namespace dmlc {
80
81 // Platform-specific definitions of a numeric thread ID type and an invalid value
82 namespace moodycamel {
83 namespace details {
84 template <typename thread_id_t>
85 struct thread_id_converter {
86 typedef thread_id_t thread_id_numeric_size_t;
87 typedef thread_id_t thread_id_hash_t;
88 static thread_id_hash_t prehash(const thread_id_t &x) {
89 return x;
90 }
91 };
92 } // namespace details
93 } // namespace moodycamel
94 #if defined(MCDBGQ_USE_RELACY)
95 namespace moodycamel {
96 namespace details {
97 typedef std::uint32_t thread_id_t;
98 static const thread_id_t invalid_thread_id = 0xFFFFFFFFU;
99 static const thread_id_t invalid_thread_id2 = 0xFFFFFFFEU;
100 static inline thread_id_t thread_id() {
101 return rl::thread_index();
102 }
103 } // namespace details
104 } // namespace moodycamel
105 #elif defined(_WIN32) || defined(__WINDOWS__) || defined(__WIN32__)
106 // No sense pulling in windows.h in a header, we'll manually declare the function
107 // we use and rely on backwards-compatibility for this not to break
108 extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void);
109 namespace moodycamel {
110 namespace details {
111 static_assert(sizeof(unsigned long) == sizeof(std::uint32_t),
112 "Expected size of unsigned long to be 32 bits on Windows");
113 typedef std::uint32_t thread_id_t;
114 static const thread_id_t invalid_thread_id
115 = 0; // See http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx
116 static const thread_id_t invalid_thread_id2
117 = 0xFFFFFFFFU; // Not technically guaranteed to be invalid, but is never used in practice. Note
118 // that all Win32 thread IDs are presently multiples of 4.
119 static inline thread_id_t thread_id() {
120 return static_cast<thread_id_t>(::GetCurrentThreadId());
121 }
122 } // namespace details
123 } // namespace moodycamel
124 #elif defined(__arm__) || defined(_M_ARM) || defined(__aarch64__) \
125 || (defined(__APPLE__) && TARGET_OS_IPHONE)
126 namespace moodycamel {
127 namespace details {
128 static_assert(sizeof(std::thread::id) == 4 || sizeof(std::thread::id) == 8,
129 "std::thread::id is expected to be either 4 or 8 bytes");
130
131 typedef std::thread::id thread_id_t;
132 static const thread_id_t invalid_thread_id; // Default ctor creates invalid ID
133
134 // Note we don't define a invalid_thread_id2 since std::thread::id doesn't have one; it's
135 // only used if MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED is defined anyway, which it won't
136 // be.
137 static inline thread_id_t thread_id() {
138 return std::this_thread::get_id();
139 }
140
141 template <std::size_t>
142 struct thread_id_size {};
143 template <>
144 struct thread_id_size<4> {
145 typedef std::uint32_t numeric_t;
146 };
147 template <>
148 struct thread_id_size<8> {
149 typedef std::uint64_t numeric_t;
150 };
151
152 template <>
153 struct thread_id_converter<thread_id_t> {
154 typedef thread_id_size<sizeof(thread_id_t)>::numeric_t thread_id_numeric_size_t;
155 #ifndef __APPLE__
156 typedef std::size_t thread_id_hash_t;
157 #else
158 typedef thread_id_numeric_size_t thread_id_hash_t;
159 #endif
160
161 static thread_id_hash_t prehash(thread_id_t const &x) {
162 #ifndef __APPLE__
163 return std::hash<std::thread::id>()(x);
164 #else
165 return *reinterpret_cast<thread_id_hash_t const *>(&x);
166 #endif
167 }
168 };
169 }
170 }
171 #else
172 // Use a nice trick from this answer: http://stackoverflow.com/a/8438730/21475
173 // In order to get a numeric thread ID in a platform-independent way, we use a thread-local
174 // static variable's address as a thread identifier :-)
175 #if defined(__GNUC__) || defined(__INTEL_COMPILER)
176 #define MOODYCAMEL_THREADLOCAL __thread
177 #elif defined(_MSC_VER)
178 #define MOODYCAMEL_THREADLOCAL __declspec(thread)
179 #else
180 // Assume C++11 compliant compiler
181 #define MOODYCAMEL_THREADLOCAL thread_local
182 #endif
183 namespace moodycamel {
184 namespace details {
185 typedef std::uintptr_t thread_id_t;
186 static const thread_id_t invalid_thread_id = 0; // Address can't be nullptr
187 static const thread_id_t invalid_thread_id2
188 = 1; // Member accesses off a null pointer are also generally invalid. Plus it's not aligned.
189 static inline thread_id_t thread_id() {
190 static MOODYCAMEL_THREADLOCAL int x;
191 return reinterpret_cast<thread_id_t>(&x);
192 }
193 }
194 }
195 #endif
196
197 // Exceptions
198 #ifndef MOODYCAMEL_EXCEPTIONS_ENABLED
199 #if (defined(_MSC_VER) && defined(_CPPUNWIND)) || (defined(__GNUC__) && defined(__EXCEPTIONS)) \
200 || (!defined(_MSC_VER) && !defined(__GNUC__))
201 #define MOODYCAMEL_EXCEPTIONS_ENABLED
202 #endif
203 #endif
204 #ifdef MOODYCAMEL_EXCEPTIONS_ENABLED
205 #define MOODYCAMEL_TRY try
206 #define MOODYCAMEL_CATCH(...) catch (__VA_ARGS__)
207 #define MOODYCAMEL_RETHROW throw
208 #define MOODYCAMEL_THROW(expr) throw(expr)
209 #else
210 #define MOODYCAMEL_TRY if (true)
211 #define MOODYCAMEL_CATCH(...) else if (false)
212 #define MOODYCAMEL_RETHROW
213 #define MOODYCAMEL_THROW(expr)
214 #endif
215
216 #ifndef MOODYCAMEL_NOEXCEPT
217 #if !defined(MOODYCAMEL_EXCEPTIONS_ENABLED)
218 #define MOODYCAMEL_NOEXCEPT
219 #define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) true
220 #define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) true
221 #elif defined(_MSC_VER) && defined(_NOEXCEPT) && _MSC_VER < 1800
222 // VS2012's std::is_nothrow_[move_]constructible is broken and returns true when it shouldn't
223 // :-( We have to assume *all* non-trivial constructors may throw on VS2012!
224 #define MOODYCAMEL_NOEXCEPT _NOEXCEPT
225 #define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) \
226 (std::is_rvalue_reference<valueType>::value && std::is_move_constructible<type>::value \
227 ? std::is_trivially_move_constructible<type>::value \
228 : std::is_trivially_copy_constructible<type>::value)
229 #define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) \
230 ((std::is_rvalue_reference<valueType>::value && std::is_move_assignable<type>::value \
231 ? std::is_trivially_move_assignable<type>::value \
232 || std::is_nothrow_move_assignable<type>::value \
233 : std::is_trivially_copy_assignable<type>::value \
234 || std::is_nothrow_copy_assignable<type>::value) \
235 && MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr))
236 #elif defined(_MSC_VER) && defined(_NOEXCEPT) && _MSC_VER < 1900
237 #define MOODYCAMEL_NOEXCEPT _NOEXCEPT
238 #define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) \
239 (std::is_rvalue_reference<valueType>::value && std::is_move_constructible<type>::value \
240 ? std::is_trivially_move_constructible<type>::value \
241 || std::is_nothrow_move_constructible<type>::value \
242 : std::is_trivially_copy_constructible<type>::value \
243 || std::is_nothrow_copy_constructible<type>::value)
244 #define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) \
245 ((std::is_rvalue_reference<valueType>::value && std::is_move_assignable<type>::value \
246 ? std::is_trivially_move_assignable<type>::value \
247 || std::is_nothrow_move_assignable<type>::value \
248 : std::is_trivially_copy_assignable<type>::value \
249 || std::is_nothrow_copy_assignable<type>::value) \
250 && MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr))
251 #else
252 #define MOODYCAMEL_NOEXCEPT noexcept
253 #define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) noexcept(expr)
254 #define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) noexcept(expr)
255 #endif
256 #endif
257
258 #ifndef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
259 #ifdef MCDBGQ_USE_RELACY
260 #define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
261 #else
262 // VS2013 doesn't support `thread_local`, and MinGW-w64 w/ POSIX threading has a crippling
263 // bug: http://sourceforge.net/p/mingw-w64/bugs/445 g++ <=4.7 doesn't support thread_local
264 // either. Finally, iOS/ARM doesn't have support for it either, and g++/ARM allows it to
265 // compile but it's unconfirmed to actually work
266 #if (!defined(_MSC_VER) || _MSC_VER >= 1900) \
267 && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) \
268 && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) \
269 && (!defined(__APPLE__) || !TARGET_OS_IPHONE) && !defined(__arm__) && !defined(_M_ARM) \
270 && !defined(__aarch64__)
271 // Assume `thread_local` is fully supported in all other C++11 compilers/platforms
272 // #define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED // always disabled for now since several
273 // users report having problems with it on
274 #endif
275 #endif
276 #endif
277
278 // VS2012 doesn't support deleted functions.
279 // In this case, we declare the function normally but don't define it. A link error will be
280 // generated if the function is called.
281 #ifndef MOODYCAMEL_DELETE_FUNCTION
282 #if defined(_MSC_VER) && _MSC_VER < 1800
283 #define MOODYCAMEL_DELETE_FUNCTION
284 #else
285 #define MOODYCAMEL_DELETE_FUNCTION = delete
286 #endif
287 #endif
288
289 // Compiler-specific likely/unlikely hints
290 namespace moodycamel {
291 namespace details {
292 #if defined(__GNUC__)
293 inline bool likely(bool x) {
294 return __builtin_expect((x), true);
295 }
296 inline bool unlikely(bool x) {
297 return __builtin_expect((x), false);
298 }
299 #else
300 inline bool likely(bool x) {
301 return x;
302 }
303 inline bool unlikely(bool x) {
304 return x;
305 }
306 #endif
307 } // namespace details
308 } // namespace moodycamel
309
310 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
311 #include "internal/concurrentqueue_internal_debug.h"
312 #endif
313
314 namespace moodycamel {
315 namespace details {
316 template <typename T>
317 struct const_numeric_max {
318 static_assert(std::is_integral<T>::value, "const_numeric_max can only be used with integers");
319 static const T value = std::numeric_limits<T>::is_signed
320 ? (static_cast<T>(1) << (sizeof(T) * CHAR_BIT - 1)) - static_cast<T>(1)
321 : static_cast<T>(-1);
322 };
323
324 #if defined(__GLIBCXX__)
325 typedef ::max_align_t std_max_align_t; // libstdc++ forgot to add it to std:: for a while
326 #else
327 typedef std::max_align_t
328 std_max_align_t; // Others (e.g. MSVC) insist it can *only* be accessed via std::
329 #endif
330
331 // Some platforms have incorrectly set max_align_t to a type with <8 bytes alignment even while
332 // supporting 8-byte aligned scalar values (*cough* 32-bit iOS). Work around this with our own
333 // union. See issue #64.
334 typedef union {
335 std_max_align_t x;
336 long long y;
337 void *z;
338 } max_align_t;
339 } // namespace details
340
341 // Default traits for the ConcurrentQueue. To change some of the
342 // traits without re-implementing all of them, inherit from this
343 // struct and shadow the declarations you wish to be different;
344 // since the traits are used as a template type parameter, the
345 // shadowed declarations will be used where defined, and the defaults
346 // otherwise.
347 struct ConcurrentQueueDefaultTraits {
348 // General-purpose size type. std::size_t is strongly recommended.
349 typedef std::size_t size_t;
350
351 // The type used for the enqueue and dequeue indices. Must be at least as
352 // large as size_t. Should be significantly larger than the number of elements
353 // you expect to hold at once, especially if you have a high turnover rate;
354 // for example, on 32-bit x86, if you expect to have over a hundred million
355 // elements or pump several million elements through your queue in a very
356 // short space of time, using a 32-bit type *may* trigger a race condition.
357 // A 64-bit int type is recommended in that case, and in practice will
358 // prevent a race condition no matter the usage of the queue. Note that
359 // whether the queue is lock-free with a 64-int type depends on the whether
360 // std::atomic<std::uint64_t> is lock-free, which is platform-specific.
361 typedef std::size_t index_t;
362
363 // Internally, all elements are enqueued and dequeued from multi-element
364 // blocks; this is the smallest controllable unit. If you expect few elements
365 // but many producers, a smaller block size should be favoured. For few producers
366 // and/or many elements, a larger block size is preferred. A sane default
367 // is provided. Must be a power of 2.
368 static const size_t BLOCK_SIZE = 32;
369
370 // For explicit producers (i.e. when using a producer token), the block is
371 // checked for being empty by iterating through a list of flags, one per element.
372 // For large block sizes, this is too inefficient, and switching to an atomic
373 // counter-based approach is faster. The switch is made for block sizes strictly
374 // larger than this threshold.
375 static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD = 32;
376
377 // How many full blocks can be expected for a single explicit producer? This should
378 // reflect that number's maximum for optimal performance. Must be a power of 2.
379 static const size_t EXPLICIT_INITIAL_INDEX_SIZE = 32;
380
381 // How many full blocks can be expected for a single implicit producer? This should
382 // reflect that number's maximum for optimal performance. Must be a power of 2.
383 static const size_t IMPLICIT_INITIAL_INDEX_SIZE = 32;
384
385 // The initial size of the hash table mapping thread IDs to implicit producers.
386 // Note that the hash is resized every time it becomes half full.
387 // Must be a power of two, and either 0 or at least 1. If 0, implicit production
388 // (using the enqueue methods without an explicit producer token) is disabled.
389 static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE = 32;
390
391 // Controls the number of items that an explicit consumer (i.e. one with a token)
392 // must consume before it causes all consumers to rotate and move on to the next
393 // internal queue.
394 static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE = 256;
395
396 // The maximum number of elements (inclusive) that can be enqueued to a sub-queue.
397 // Enqueue operations that would cause this limit to be surpassed will fail. Note
398 // that this limit is enforced at the block level (for performance reasons), i.e.
399 // it's rounded up to the nearest block size.
400 static const size_t MAX_SUBQUEUE_SIZE = details::const_numeric_max<size_t>::value;
401
402 #ifndef MCDBGQ_USE_RELACY
403 // Memory allocation can be customized if needed.
404 // malloc should return nullptr on failure, and handle alignment like std::malloc.
405 #if defined(malloc) || defined(free)
406 // Gah, this is 2015, stop defining macros that break standard code already!
407 // Work around malloc/free being special macros:
408 static inline void *WORKAROUND_malloc(size_t size) {
409 return malloc(size);
410 }
411 static inline void WORKAROUND_free(void *ptr) {
412 return free(ptr);
413 }
414 static inline void *(malloc)(size_t size) {
415 return WORKAROUND_malloc(size);
416 }
417 static inline void(free)(void *ptr) {
418 return WORKAROUND_free(ptr);
419 }
420 #else
421 static inline void *malloc(size_t size) {
422 return std::malloc(size);
423 }
424 static inline void free(void *ptr) {
425 return std::free(ptr);
426 }
427 #endif
428 #else
429 // Debug versions when running under the Relacy race detector (ignore
430 // these in user code)
431 static inline void *malloc(size_t size) {
432 return rl::rl_malloc(size, $);
433 }
434 static inline void free(void *ptr) {
435 return rl::rl_free(ptr, $);
436 }
437 #endif
438 };
439
440 // When producing or consuming many elements, the most efficient way is to:
441 // 1) Use one of the bulk-operation methods of the queue with a token
442 // 2) Failing that, use the bulk-operation methods without a token
443 // 3) Failing that, create a token and use that with the single-item methods
444 // 4) Failing that, use the single-parameter methods of the queue
445 // Having said that, don't create tokens willy-nilly -- ideally there should be
446 // a maximum of one token per thread (of each kind).
447 struct ProducerToken;
448 struct ConsumerToken;
449
450 template <typename T, typename Traits>
451 class ConcurrentQueue;
452 template <typename T, typename Traits>
453 class BlockingConcurrentQueue;
454 class ConcurrentQueueTests;
455
456 namespace details {
457 struct ConcurrentQueueProducerTypelessBase {
458 ConcurrentQueueProducerTypelessBase *next;
459 std::atomic<bool> inactive;
460 ProducerToken *token;
461
462 ConcurrentQueueProducerTypelessBase() : next(nullptr), inactive(false), token(nullptr) {}
463 };
464
465 template <bool use32>
466 struct _hash_32_or_64 {
467 static inline std::uint32_t hash(std::uint32_t h) {
468 // MurmurHash3 finalizer -- see
469 // https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp Since the thread ID is
470 // already unique, all we really want to do is propagate that uniqueness evenly across all the
471 // bits, so that we can use a subset of the bits while reducing collisions significantly
472 h ^= h >> 16;
473 h *= 0x85ebca6b;
474 h ^= h >> 13;
475 h *= 0xc2b2ae35;
476 return h ^ (h >> 16);
477 }
478 };
479 template <>
480 struct _hash_32_or_64<1> {
481 static inline std::uint64_t hash(std::uint64_t h) {
482 h ^= h >> 33;
483 h *= 0xff51afd7ed558ccd;
484 h ^= h >> 33;
485 h *= 0xc4ceb9fe1a85ec53;
486 return h ^ (h >> 33);
487 }
488 };
489 template <std::size_t size>
490 struct hash_32_or_64 : public _hash_32_or_64<(size > 4)> {};
491
492 static inline size_t hash_thread_id(thread_id_t id) {
493 static_assert(
494 sizeof(thread_id_t) <= 8, "Expected a platform where thread IDs are at most 64-bit values");
495 return static_cast<size_t>(
496 hash_32_or_64<sizeof(thread_id_converter<thread_id_t>::thread_id_hash_t)>::hash(
497 thread_id_converter<thread_id_t>::prehash(id)));
498 }
499
500 template <typename T>
501 static inline bool circular_less_than(T a, T b) {
502 #ifdef _MSC_VER
503
504
505 #endif
506 static_assert(std::is_integral<T>::value && !std::numeric_limits<T>::is_signed,
507 "circular_less_than is intended to be used only with unsigned integer types");
508 return static_cast<T>(a - b)
509 > static_cast<T>(static_cast<T>(1) << static_cast<T>(sizeof(T) * CHAR_BIT - 1));
510 #ifdef _MSC_VER
511
512 #endif
513 }
514
515 template <typename U>
516 static inline char *align_for(char *ptr) {
517 const std::size_t alignment = std::alignment_of<U>::value;
518 return ptr + (alignment - (reinterpret_cast<std::uintptr_t>(ptr) % alignment)) % alignment;
519 }
520
521 template <typename T>
522 static inline T ceil_to_pow_2(T x) {
523 static_assert(std::is_integral<T>::value && !std::numeric_limits<T>::is_signed,
524 "ceil_to_pow_2 is intended to be used only with unsigned integer types");
525
526 // Adapted from http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
527 --x;
528 x |= x >> 1;
529 x |= x >> 2;
530 x |= x >> 4;
531 for (std::size_t i = 1; i < sizeof(T); i <<= 1) {
532 x |= x >> (i << 3);
533 }
534 ++x;
535 return x;
536 }
537
538 template <typename T>
539 static inline void swap_relaxed(std::atomic<T> &left, std::atomic<T> &right) {
540 T temp = std::move(left.load(std::memory_order_relaxed));
541 left.store(std::move(right.load(std::memory_order_relaxed)), std::memory_order_relaxed);
542 right.store(std::move(temp), std::memory_order_relaxed);
543 }
544
545 template <typename T>
546 static inline const T &nomove(const T &x) {
547 return x;
548 }
549
550 template <bool Enable>
551 struct nomove_if {
552 template <typename T>
553 static inline const T &eval(const T &x) {
554 return x;
555 }
556 };
557
558 template <>
559 struct nomove_if<false> {
560 template <typename U>
561 static inline auto eval(U &&x) -> decltype(std::forward<U>(x)) {
562 return std::forward<U>(x);
563 }
564 };
565
566 template <typename It>
567 static inline auto deref_noexcept(It &it) MOODYCAMEL_NOEXCEPT -> decltype(*it) {
568 return *it;
569 }
570
571 #if defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 4 \
572 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
573 template <typename T>
574 struct is_trivially_destructible : std::is_trivially_destructible<T> {};
575 #else
576 template <typename T>
577 struct is_trivially_destructible : std::has_trivial_destructor<T> {};
578 #endif
579
580 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
581 #ifdef MCDBGQ_USE_RELACY
582 typedef RelacyThreadExitListener ThreadExitListener;
583 typedef RelacyThreadExitNotifier ThreadExitNotifier;
584 #else
585 struct ThreadExitListener {
586 typedef void (*callback_t)(void *);
587 callback_t callback;
588 void *userData;
589
590 ThreadExitListener *next; // reserved for use by the ThreadExitNotifier
591 };
592
593 class ThreadExitNotifier {
594 public:
595 static void subscribe(ThreadExitListener *listener) {
596 auto &tlsInst = instance();
597 listener->next = tlsInst.tail;
598 tlsInst.tail = listener;
599 }
600
601 static void unsubscribe(ThreadExitListener *listener) {
602 auto &tlsInst = instance();
603 ThreadExitListener **prev = &tlsInst.tail;
604 for (auto ptr = tlsInst.tail; ptr != nullptr; ptr = ptr->next) {
605 if (ptr == listener) {
606 *prev = ptr->next;
607 break;
608 }
609 prev = &ptr->next;
610 }
611 }
612
613 private:
614 ThreadExitNotifier() : tail(nullptr) {}
615 ThreadExitNotifier(const ThreadExitNotifier &) MOODYCAMEL_DELETE_FUNCTION;
616 ThreadExitNotifier &operator=(const ThreadExitNotifier &) MOODYCAMEL_DELETE_FUNCTION;
617
618 ~ThreadExitNotifier() {
619 // This thread is about to exit, let everyone know!
620 assert(this == &instance() && "If this assert fails, you likely have a buggy compiler! Change the preprocessor conditions such that MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED is no longer defined.");
621 for (auto ptr = tail; ptr != nullptr; ptr = ptr->next) {
622 ptr->callback(ptr->userData);
623 }
624 }
625
626 // Thread-local
627 static inline ThreadExitNotifier &instance() {
628 static thread_local ThreadExitNotifier notifier;
629 return notifier;
630 }
631
632 private:
633 ThreadExitListener *tail;
634 };
635 #endif
636 #endif
637
638 template <typename T>
639 struct static_is_lock_free_num {
640 enum { value = 0 };
641 };
642 template <>
643 struct static_is_lock_free_num<signed char> {
644 enum { value = ATOMIC_CHAR_LOCK_FREE };
645 };
646 template <>
647 struct static_is_lock_free_num<short> {
648 enum { value = ATOMIC_SHORT_LOCK_FREE };
649 };
650 template <>
651 struct static_is_lock_free_num<int> {
652 enum { value = ATOMIC_INT_LOCK_FREE };
653 };
654 template <>
655 struct static_is_lock_free_num<long> {
656 enum { value = ATOMIC_LONG_LOCK_FREE };
657 };
658 template <>
659 struct static_is_lock_free_num<long long> {
660 enum { value = ATOMIC_LLONG_LOCK_FREE };
661 };
662 template <typename T>
663 struct static_is_lock_free : static_is_lock_free_num<typename std::make_signed<T>::type> {};
664 template <>
665 struct static_is_lock_free<bool> {
666 enum { value = ATOMIC_BOOL_LOCK_FREE };
667 };
668 template <typename U>
669 struct static_is_lock_free<U *> {
670 enum { value = ATOMIC_POINTER_LOCK_FREE };
671 };
672 } // namespace details
673
674 struct ProducerToken {
675 template <typename T, typename Traits>
676 explicit ProducerToken(ConcurrentQueue<T, Traits> &queue);
677
678 template <typename T, typename Traits>
679 explicit ProducerToken(BlockingConcurrentQueue<T, Traits> &queue);
680
681 ProducerToken(ProducerToken &&other) MOODYCAMEL_NOEXCEPT : producer(other.producer) {
682 other.producer = nullptr;
683 if (producer != nullptr) {
684 producer->token = this;
685 }
686 }
687
688 inline ProducerToken &operator=(ProducerToken &&other) MOODYCAMEL_NOEXCEPT {
689 swap(other);
690 return *this;
691 }
692
693 void swap(ProducerToken &other) MOODYCAMEL_NOEXCEPT {
694 std::swap(producer, other.producer);
695 if (producer != nullptr) {
696 producer->token = this;
697 }
698 if (other.producer != nullptr) {
699 other.producer->token = &other;
700 }
701 }
702
703 // A token is always valid unless:
704 // 1) Memory allocation failed during construction
705 // 2) It was moved via the move constructor
706 // (Note: assignment does a swap, leaving both potentially valid)
707 // 3) The associated queue was destroyed
708 // Note that if valid() returns true, that only indicates
709 // that the token is valid for use with a specific queue,
710 // but not which one; that's up to the user to track.
711 inline bool valid() const {
712 return producer != nullptr;
713 }
714
715 ~ProducerToken() {
716 if (producer != nullptr) {
717 producer->token = nullptr;
718 producer->inactive.store(true, std::memory_order_release);
719 }
720 }
721
722 // Disable copying and assignment
723 ProducerToken(const ProducerToken &) MOODYCAMEL_DELETE_FUNCTION;
724 ProducerToken &operator=(const ProducerToken &) MOODYCAMEL_DELETE_FUNCTION;
725
726 private:
727 template <typename T, typename Traits>
728 friend class ConcurrentQueue;
729 friend class ConcurrentQueueTests;
730
731 protected:
732 details::ConcurrentQueueProducerTypelessBase *producer;
733 };
734
735 struct ConsumerToken {
736 template <typename T, typename Traits>
737 explicit ConsumerToken(ConcurrentQueue<T, Traits> &q);
738
739 template <typename T, typename Traits>
740 explicit ConsumerToken(BlockingConcurrentQueue<T, Traits> &q);
741
742 ConsumerToken(ConsumerToken &&other) MOODYCAMEL_NOEXCEPT :
743 initialOffset(other.initialOffset),
744 lastKnownGlobalOffset(other.lastKnownGlobalOffset),
745 itemsConsumedFromCurrent(other.itemsConsumedFromCurrent),
746 currentProducer(other.currentProducer),
747 desiredProducer(other.desiredProducer) {}
748
749 inline ConsumerToken &operator=(ConsumerToken &&other) MOODYCAMEL_NOEXCEPT {
750 swap(other);
751 return *this;
752 }
753
754 void swap(ConsumerToken &other) MOODYCAMEL_NOEXCEPT {
755 std::swap(initialOffset, other.initialOffset);
756 std::swap(lastKnownGlobalOffset, other.lastKnownGlobalOffset);
757 std::swap(itemsConsumedFromCurrent, other.itemsConsumedFromCurrent);
758 std::swap(currentProducer, other.currentProducer);
759 std::swap(desiredProducer, other.desiredProducer);
760 }
761
762 // Disable copying and assignment
763 ConsumerToken(const ConsumerToken &) MOODYCAMEL_DELETE_FUNCTION;
764 ConsumerToken &operator=(const ConsumerToken &) MOODYCAMEL_DELETE_FUNCTION;
765
766 private:
767 template <typename T, typename Traits>
768 friend class ConcurrentQueue;
769 friend class ConcurrentQueueTests;
770
771 private: // but shared with ConcurrentQueue
772 std::uint32_t initialOffset;
773 std::uint32_t lastKnownGlobalOffset;
774 std::uint32_t itemsConsumedFromCurrent;
775 details::ConcurrentQueueProducerTypelessBase *currentProducer;
776 details::ConcurrentQueueProducerTypelessBase *desiredProducer;
777 };
778
779 // Need to forward-declare this swap because it's in a namespace.
780 // See
781 // http://stackoverflow.com/questions/4492062/why-does-a-c-friend-class-need-a-forward-declaration-only-in-other-namespaces
782 template <typename T, typename Traits>
783 inline void swap(typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP &a,
784 typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP &b) MOODYCAMEL_NOEXCEPT;
785
786 template <typename T, typename Traits = ConcurrentQueueDefaultTraits>
787 class ConcurrentQueue {
788 public:
789 typedef ::dmlc::moodycamel::ProducerToken producer_token_t;
790 typedef ::dmlc::moodycamel::ConsumerToken consumer_token_t;
791
792 typedef typename Traits::index_t index_t;
793 typedef typename Traits::size_t size_t;
794
795 static const size_t BLOCK_SIZE = static_cast<size_t>(Traits::BLOCK_SIZE);
796 static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD
797 = static_cast<size_t>(Traits::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD);
798 static const size_t EXPLICIT_INITIAL_INDEX_SIZE
799 = static_cast<size_t>(Traits::EXPLICIT_INITIAL_INDEX_SIZE);
800 static const size_t IMPLICIT_INITIAL_INDEX_SIZE
801 = static_cast<size_t>(Traits::IMPLICIT_INITIAL_INDEX_SIZE);
802 static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
803 = static_cast<size_t>(Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE);
804 static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE
805 = static_cast<std::uint32_t>(Traits::EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE);
806 #ifdef _MSC_VER
807
808
809 // expression is for!)
810
811 #endif
812 static const size_t MAX_SUBQUEUE_SIZE
813 = (details::const_numeric_max<size_t>::value - static_cast<size_t>(Traits::MAX_SUBQUEUE_SIZE)
814 < BLOCK_SIZE)
815 ? details::const_numeric_max<size_t>::value
816 : ((static_cast<size_t>(Traits::MAX_SUBQUEUE_SIZE) + (BLOCK_SIZE - 1)) / BLOCK_SIZE
817 * BLOCK_SIZE);
818 #ifdef _MSC_VER
819
820 #endif
821
822 static_assert(!std::numeric_limits<size_t>::is_signed && std::is_integral<size_t>::value,
823 "Traits::size_t must be an unsigned integral type");
824 static_assert(!std::numeric_limits<index_t>::is_signed && std::is_integral<index_t>::value,
825 "Traits::index_t must be an unsigned integral type");
826 static_assert(sizeof(index_t) >= sizeof(size_t),
827 "Traits::index_t must be at least as wide as Traits::size_t");
828 static_assert((BLOCK_SIZE > 1) && !(BLOCK_SIZE & (BLOCK_SIZE - 1)),
829 "Traits::BLOCK_SIZE must be a power of 2 (and at least 2)");
830 static_assert((EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD > 1)
831 && !(EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD
832 & (EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD - 1)),
833 "Traits::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD must be a power of 2 (and greater than 1)");
834 static_assert((EXPLICIT_INITIAL_INDEX_SIZE > 1)
835 && !(EXPLICIT_INITIAL_INDEX_SIZE & (EXPLICIT_INITIAL_INDEX_SIZE - 1)),
836 "Traits::EXPLICIT_INITIAL_INDEX_SIZE must be a power of 2 (and greater than 1)");
837 static_assert((IMPLICIT_INITIAL_INDEX_SIZE > 1)
838 && !(IMPLICIT_INITIAL_INDEX_SIZE & (IMPLICIT_INITIAL_INDEX_SIZE - 1)),
839 "Traits::IMPLICIT_INITIAL_INDEX_SIZE must be a power of 2 (and greater than 1)");
840 static_assert(
841 (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0)
842 || !(INITIAL_IMPLICIT_PRODUCER_HASH_SIZE & (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE - 1)),
843 "Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE must be a power of 2");
844 static_assert(
845 INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0 || INITIAL_IMPLICIT_PRODUCER_HASH_SIZE >= 1,
846 "Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE must be at least 1 (or 0 to disable implicit "
847 "enqueueing)");
848
849 public:
850 // Creates a queue with at least `capacity` element slots; note that the
851 // actual number of elements that can be inserted without additional memory
852 // allocation depends on the number of producers and the block size (e.g. if
853 // the block size is equal to `capacity`, only a single block will be allocated
854 // up-front, which means only a single producer will be able to enqueue elements
855 // without an extra allocation -- blocks aren't shared between producers).
856 // This method is not thread safe -- it is up to the user to ensure that the
857 // queue is fully constructed before it starts being used by other threads (this
858 // includes making the memory effects of construction visible, possibly with a
859 // memory barrier).
860 explicit ConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE)
861 : producerListTail(nullptr),
862 producerCount(0),
863 initialBlockPoolIndex(0),
864 nextExplicitConsumerId(0),
865 globalExplicitConsumerOffset(0) {
866 implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
867 populate_initial_implicit_producer_hash();
868 populate_initial_block_list(
869 capacity / BLOCK_SIZE + ((capacity & (BLOCK_SIZE - 1)) == 0 ? 0 : 1));
870
871 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
872 // Track all the producers using a fully-resolved typed list for
873 // each kind; this makes it possible to debug them starting from
874 // the root queue object (otherwise wacky casts are needed that
875 // don't compile in the debugger's expression evaluator).
876 explicitProducers.store(nullptr, std::memory_order_relaxed);
877 implicitProducers.store(nullptr, std::memory_order_relaxed);
878 #endif
879 }
880
881 // Computes the correct amount of pre-allocated blocks for you based
882 // on the minimum number of elements you want available at any given
883 // time, and the maximum concurrent number of each type of producer.
884 ConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers)
885 : producerListTail(nullptr),
886 producerCount(0),
887 initialBlockPoolIndex(0),
888 nextExplicitConsumerId(0),
889 globalExplicitConsumerOffset(0) {
890 implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
891 populate_initial_implicit_producer_hash();
892 size_t blocks = (((minCapacity + BLOCK_SIZE - 1) / BLOCK_SIZE) - 1) * (maxExplicitProducers + 1)
893 + 2 * (maxExplicitProducers + maxImplicitProducers);
894 populate_initial_block_list(blocks);
895
896 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
897 explicitProducers.store(nullptr, std::memory_order_relaxed);
898 implicitProducers.store(nullptr, std::memory_order_relaxed);
899 #endif
900 }
901
902 // Note: The queue should not be accessed concurrently while it's
903 // being deleted. It's up to the user to synchronize this.
904 // This method is not thread safe.
905 ~ConcurrentQueue() {
906 // Destroy producers
907 auto ptr = producerListTail.load(std::memory_order_relaxed);
908 while (ptr != nullptr) {
909 auto next = ptr->next_prod();
910 if (ptr->token != nullptr) {
911 ptr->token->producer = nullptr;
912 }
913 destroy(ptr);
914 ptr = next;
915 }
916
917 // Destroy implicit producer hash tables
918 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE != 0) {
919 auto hash = implicitProducerHash.load(std::memory_order_relaxed);
920 while (hash != nullptr) {
921 auto prev = hash->prev;
922 if (prev
923 != nullptr) { // The last hash is part of this object and was not allocated dynamically
924 for (size_t i = 0; i != hash->capacity; ++i) {
925 hash->entries[i].~ImplicitProducerKVP();
926 }
927 hash->~ImplicitProducerHash();
928 (Traits::free)(hash);
929 }
930 hash = prev;
931 }
932 }
933
934 // Destroy global free list
935 auto block = freeList.head_unsafe();
936 while (block != nullptr) {
937 auto next = block->freeListNext.load(std::memory_order_relaxed);
938 if (block->dynamicallyAllocated) {
939 destroy(block);
940 }
941 block = next;
942 }
943
944 // Destroy initial free list
945 destroy_array(initialBlockPool, initialBlockPoolSize);
946 }
947
948 // Disable copying and copy assignment
949 ConcurrentQueue(const ConcurrentQueue &) MOODYCAMEL_DELETE_FUNCTION;
950
951 ConcurrentQueue &operator=(const ConcurrentQueue &) MOODYCAMEL_DELETE_FUNCTION;
952
953 // Moving is supported, but note that it is *not* a thread-safe operation.
954 // Nobody can use the queue while it's being moved, and the memory effects
955 // of that move must be propagated to other threads before they can use it.
956 // Note: When a queue is moved, its tokens are still valid but can only be
957 // used with the destination queue (i.e. semantically they are moved along
958 // with the queue itself).
959 ConcurrentQueue(ConcurrentQueue &&other) MOODYCAMEL_NOEXCEPT :
960 producerListTail(other.producerListTail.load(std::memory_order_relaxed)),
961 producerCount(other.producerCount.load(std::memory_order_relaxed)),
962 initialBlockPoolIndex(other.initialBlockPoolIndex.load(std::memory_order_relaxed)),
963 initialBlockPool(other.initialBlockPool),
964 initialBlockPoolSize(other.initialBlockPoolSize),
965 freeList(std::move(other.freeList)),
966 nextExplicitConsumerId(other.nextExplicitConsumerId.load(std::memory_order_relaxed)),
967 globalExplicitConsumerOffset(
968 other.globalExplicitConsumerOffset.load(std::memory_order_relaxed)) {
969 // Move the other one into this, and leave the other one as an empty queue
970 implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
971 populate_initial_implicit_producer_hash();
972 swap_implicit_producer_hashes(other);
973
974 other.producerListTail.store(nullptr, std::memory_order_relaxed);
975 other.producerCount.store(0, std::memory_order_relaxed);
976 other.nextExplicitConsumerId.store(0, std::memory_order_relaxed);
977 other.globalExplicitConsumerOffset.store(0, std::memory_order_relaxed);
978
979 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
980 explicitProducers.store(
981 other.explicitProducers.load(std::memory_order_relaxed), std::memory_order_relaxed);
982 other.explicitProducers.store(nullptr, std::memory_order_relaxed);
983 implicitProducers.store(
984 other.implicitProducers.load(std::memory_order_relaxed), std::memory_order_relaxed);
985 other.implicitProducers.store(nullptr, std::memory_order_relaxed);
986 #endif
987
988 other.initialBlockPoolIndex.store(0, std::memory_order_relaxed);
989 other.initialBlockPoolSize = 0;
990 other.initialBlockPool = nullptr;
991
992 reown_producers();
993 }
994
995 inline ConcurrentQueue &operator=(ConcurrentQueue &&other) MOODYCAMEL_NOEXCEPT {
996 return swap_internal(other);
997 }
998
999 // Swaps this queue's state with the other's. Not thread-safe.
1000 // Swapping two queues does not invalidate their tokens, however
1001 // the tokens that were created for one queue must be used with
1002 // only the swapped queue (i.e. the tokens are tied to the
1003 // queue's movable state, not the object itself).
1004 inline void swap(ConcurrentQueue &other) MOODYCAMEL_NOEXCEPT {
1005 swap_internal(other);
1006 }
1007
1008 private:
1009 ConcurrentQueue &swap_internal(ConcurrentQueue &other) {
1010 if (this == &other) {
1011 return *this;
1012 }
1013
1014 details::swap_relaxed(producerListTail, other.producerListTail);
1015 details::swap_relaxed(producerCount, other.producerCount);
1016 details::swap_relaxed(initialBlockPoolIndex, other.initialBlockPoolIndex);
1017 std::swap(initialBlockPool, other.initialBlockPool);
1018 std::swap(initialBlockPoolSize, other.initialBlockPoolSize);
1019 freeList.swap(other.freeList);
1020 details::swap_relaxed(nextExplicitConsumerId, other.nextExplicitConsumerId);
1021 details::swap_relaxed(globalExplicitConsumerOffset, other.globalExplicitConsumerOffset);
1022
1023 swap_implicit_producer_hashes(other);
1024
1025 reown_producers();
1026 other.reown_producers();
1027
1028 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
1029 details::swap_relaxed(explicitProducers, other.explicitProducers);
1030 details::swap_relaxed(implicitProducers, other.implicitProducers);
1031 #endif
1032
1033 return *this;
1034 }
1035
1036 public:
1037 // Enqueues a single item (by copying it).
1038 // Allocates memory if required. Only fails if memory allocation fails (or implicit
1039 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
1040 // or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1041 // Thread-safe.
1042 inline bool enqueue(const T &item) {
1043 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1044 return false;
1045 }
1046 return inner_enqueue<CanAlloc>(item);
1047 }
1048
1049 // Enqueues a single item (by moving it, if possible).
1050 // Allocates memory if required. Only fails if memory allocation fails (or implicit
1051 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
1052 // or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1053 // Thread-safe.
1054 inline bool enqueue(T &&item) {
1055 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1056 return false;
1057 }
1058 return inner_enqueue<CanAlloc>(std::move(item));
1059 }
1060
1061 // Enqueues a single item (by copying it) using an explicit producer token.
1062 // Allocates memory if required. Only fails if memory allocation fails (or
1063 // Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1064 // Thread-safe.
1065 inline bool enqueue(const producer_token_t &token, const T &item) {
1066 return inner_enqueue<CanAlloc>(token, item);
1067 }
1068
1069 // Enqueues a single item (by moving it, if possible) using an explicit producer token.
1070 // Allocates memory if required. Only fails if memory allocation fails (or
1071 // Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1072 // Thread-safe.
1073 inline bool enqueue(const producer_token_t &token, T &&item) {
1074 return inner_enqueue<CanAlloc>(token, std::move(item));
1075 }
1076
1077 // Enqueues several items.
1078 // Allocates memory if required. Only fails if memory allocation fails (or
1079 // implicit production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
1080 // is 0, or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1081 // Note: Use std::make_move_iterator if the elements should be moved instead of copied.
1082 // Thread-safe.
1083 template <typename It>
1084 bool enqueue_bulk(It itemFirst, size_t count) {
1085 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1086 return false;
1087 }
1088 return inner_enqueue_bulk<CanAlloc>(itemFirst, count);
1089 }
1090
1091 // Enqueues several items using an explicit producer token.
1092 // Allocates memory if required. Only fails if memory allocation fails
1093 // (or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
1094 // Note: Use std::make_move_iterator if the elements should be moved
1095 // instead of copied.
1096 // Thread-safe.
1097 template <typename It>
1098 bool enqueue_bulk(const producer_token_t &token, It itemFirst, size_t count) {
1099 return inner_enqueue_bulk<CanAlloc>(token, itemFirst, count);
1100 }
1101
1102 // Enqueues a single item (by copying it).
1103 // Does not allocate memory. Fails if not enough room to enqueue (or implicit
1104 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
1105 // is 0).
1106 // Thread-safe.
1107 inline bool try_enqueue(const T &item) {
1108 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1109 return false;
1110 }
1111 return inner_enqueue<CannotAlloc>(item);
1112 }
1113
1114 // Enqueues a single item (by moving it, if possible).
1115 // Does not allocate memory (except for one-time implicit producer).
1116 // Fails if not enough room to enqueue (or implicit production is
1117 // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
1118 // Thread-safe.
1119 inline bool try_enqueue(T &&item) {
1120 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1121 return false;
1122 }
1123 return inner_enqueue<CannotAlloc>(std::move(item));
1124 }
1125
1126 // Enqueues a single item (by copying it) using an explicit producer token.
1127 // Does not allocate memory. Fails if not enough room to enqueue.
1128 // Thread-safe.
1129 inline bool try_enqueue(const producer_token_t &token, const T &item) {
1130 return inner_enqueue<CannotAlloc>(token, item);
1131 }
1132
1133 // Enqueues a single item (by moving it, if possible) using an explicit producer token.
1134 // Does not allocate memory. Fails if not enough room to enqueue.
1135 // Thread-safe.
1136 inline bool try_enqueue(const producer_token_t &token, T &&item) {
1137 return inner_enqueue<CannotAlloc>(token, std::move(item));
1138 }
1139
1140 // Enqueues several items.
1141 // Does not allocate memory (except for one-time implicit producer).
1142 // Fails if not enough room to enqueue (or implicit production is
1143 // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
1144 // Note: Use std::make_move_iterator if the elements should be moved
1145 // instead of copied.
1146 // Thread-safe.
1147 template <typename It>
1148 bool try_enqueue_bulk(It itemFirst, size_t count) {
1149 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
1150 return false;
1151 }
1152 return inner_enqueue_bulk<CannotAlloc>(itemFirst, count);
1153 }
1154
1155 // Enqueues several items using an explicit producer token.
1156 // Does not allocate memory. Fails if not enough room to enqueue.
1157 // Note: Use std::make_move_iterator if the elements should be moved
1158 // instead of copied.
1159 // Thread-safe.
1160 template <typename It>
1161 bool try_enqueue_bulk(const producer_token_t &token, It itemFirst, size_t count) {
1162 return inner_enqueue_bulk<CannotAlloc>(token, itemFirst, count);
1163 }
1164
1165 // Attempts to dequeue from the queue.
1166 // Returns false if all producer streams appeared empty at the time they
1167 // were checked (so, the queue is likely but not guaranteed to be empty).
1168 // Never allocates. Thread-safe.
1169 template <typename U>
1170 bool try_dequeue(U &item) {
1171 // Instead of simply trying each producer in turn (which could cause needless contention on the
1172 // first producer), we score them heuristically.
1173 size_t nonEmptyCount = 0;
1174 ProducerBase *best = nullptr;
1175 size_t bestSize = 0;
1176 for (auto ptr = producerListTail.load(std::memory_order_acquire);
1177 nonEmptyCount < 3 && ptr != nullptr; ptr = ptr->next_prod()) {
1178 auto size = ptr->size_approx();
1179 if (size > 0) {
1180 if (size > bestSize) {
1181 bestSize = size;
1182 best = ptr;
1183 }
1184 ++nonEmptyCount;
1185 }
1186 }
1187
1188 // If there was at least one non-empty queue but it appears empty at the time
1189 // we try to dequeue from it, we need to make sure every queue's been tried
1190 if (nonEmptyCount > 0) {
1191 if (details::likely(best->dequeue(item))) {
1192 return true;
1193 }
1194 for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr;
1195 ptr = ptr->next_prod()) {
1196 if (ptr != best && ptr->dequeue(item)) {
1197 return true;
1198 }
1199 }
1200 }
1201 return false;
1202 }
1203
1204 // Attempts to dequeue from the queue.
1205 // Returns false if all producer streams appeared empty at the time they
1206 // were checked (so, the queue is likely but not guaranteed to be empty).
1207 // This differs from the try_dequeue(item) method in that this one does
1208 // not attempt to reduce contention by interleaving the order that producer
1209 // streams are dequeued from. So, using this method can reduce overall throughput
1210 // under contention, but will give more predictable results in single-threaded
1211 // consumer scenarios. This is mostly only useful for internal unit tests.
1212 // Never allocates. Thread-safe.
1213 template <typename U>
1214 bool try_dequeue_non_interleaved(U &item) {
1215 for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr;
1216 ptr = ptr->next_prod()) {
1217 if (ptr->dequeue(item)) {
1218 return true;
1219 }
1220 }
1221 return false;
1222 }
1223
1224 // Attempts to dequeue from the queue using an explicit consumer token.
1225 // Returns false if all producer streams appeared empty at the time they
1226 // were checked (so, the queue is likely but not guaranteed to be empty).
1227 // Never allocates. Thread-safe.
1228 template <typename U>
1229 bool try_dequeue(consumer_token_t &token, U &item) {
1230 // The idea is roughly as follows:
1231 // Every 256 items from one producer, make everyone rotate (increase the global offset) -> this
1232 // means the highest efficiency consumer dictates the rotation speed of everyone else, more or
1233 // less If you see that the global offset has changed, you must reset your consumption counter
1234 // and move to your designated place If there's no items where you're supposed to be, keep
1235 // moving until you find a producer with some items If the global offset has not changed but
1236 // you've run out of items to consume, move over from your current position until you find an
1237 // producer with something in it
1238
1239 if (token.desiredProducer == nullptr
1240 || token.lastKnownGlobalOffset
1241 != globalExplicitConsumerOffset.load(std::memory_order_relaxed)) {
1242 if (!update_current_producer_after_rotation(token)) {
1243 return false;
1244 }
1245 }
1246
1247 // If there was at least one non-empty queue but it appears empty at the time
1248 // we try to dequeue from it, we need to make sure every queue's been tried
1249 if (static_cast<ProducerBase *>(token.currentProducer)->dequeue(item)) {
1250 if (++token.itemsConsumedFromCurrent == EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE) {
1251 globalExplicitConsumerOffset.fetch_add(1, std::memory_order_relaxed);
1252 }
1253 return true;
1254 }
1255
1256 auto tail = producerListTail.load(std::memory_order_acquire);
1257 auto ptr = static_cast<ProducerBase *>(token.currentProducer)->next_prod();
1258 if (ptr == nullptr) {
1259 ptr = tail;
1260 }
1261 while (ptr != static_cast<ProducerBase *>(token.currentProducer)) {
1262 if (ptr->dequeue(item)) {
1263 token.currentProducer = ptr;
1264 token.itemsConsumedFromCurrent = 1;
1265 return true;
1266 }
1267 ptr = ptr->next_prod();
1268 if (ptr == nullptr) {
1269 ptr = tail;
1270 }
1271 }
1272 return false;
1273 }
1274
1275 // Attempts to dequeue several elements from the queue.
1276 // Returns the number of items actually dequeued.
1277 // Returns 0 if all producer streams appeared empty at the time they
1278 // were checked (so, the queue is likely but not guaranteed to be empty).
1279 // Never allocates. Thread-safe.
1280 template <typename It>
1281 size_t try_dequeue_bulk(It itemFirst, size_t max) {
1282 size_t count = 0;
1283 for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr;
1284 ptr = ptr->next_prod()) {
1285 count += ptr->dequeue_bulk(itemFirst, max - count);
1286 if (count == max) {
1287 break;
1288 }
1289 }
1290 return count;
1291 }
1292
1293 // Attempts to dequeue several elements from the queue using an explicit consumer token.
1294 // Returns the number of items actually dequeued.
1295 // Returns 0 if all producer streams appeared empty at the time they
1296 // were checked (so, the queue is likely but not guaranteed to be empty).
1297 // Never allocates. Thread-safe.
1298 template <typename It>
1299 size_t try_dequeue_bulk(consumer_token_t &token, It itemFirst, size_t max) {
1300 if (token.desiredProducer == nullptr
1301 || token.lastKnownGlobalOffset
1302 != globalExplicitConsumerOffset.load(std::memory_order_relaxed)) {
1303 if (!update_current_producer_after_rotation(token)) {
1304 return 0;
1305 }
1306 }
1307
1308 size_t count = static_cast<ProducerBase *>(token.currentProducer)->dequeue_bulk(itemFirst, max);
1309 if (count == max) {
1310 if ((token.itemsConsumedFromCurrent += static_cast<std::uint32_t>(max))
1311 >= EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE) {
1312 globalExplicitConsumerOffset.fetch_add(1, std::memory_order_relaxed);
1313 }
1314 return max;
1315 }
1316 token.itemsConsumedFromCurrent += static_cast<std::uint32_t>(count);
1317 max -= count;
1318
1319 auto tail = producerListTail.load(std::memory_order_acquire);
1320 auto ptr = static_cast<ProducerBase *>(token.currentProducer)->next_prod();
1321 if (ptr == nullptr) {
1322 ptr = tail;
1323 }
1324 while (ptr != static_cast<ProducerBase *>(token.currentProducer)) {
1325 auto dequeued = ptr->dequeue_bulk(itemFirst, max);
1326 count += dequeued;
1327 if (dequeued != 0) {
1328 token.currentProducer = ptr;
1329 token.itemsConsumedFromCurrent = static_cast<std::uint32_t>(dequeued);
1330 }
1331 if (dequeued == max) {
1332 break;
1333 }
1334 max -= dequeued;
1335 ptr = ptr->next_prod();
1336 if (ptr == nullptr) {
1337 ptr = tail;
1338 }
1339 }
1340 return count;
1341 }
1342
1343 // Attempts to dequeue from a specific producer's inner queue.
1344 // If you happen to know which producer you want to dequeue from, this
1345 // is significantly faster than using the general-case try_dequeue methods.
1346 // Returns false if the producer's queue appeared empty at the time it
1347 // was checked (so, the queue is likely but not guaranteed to be empty).
1348 // Never allocates. Thread-safe.
1349 template <typename U>
1350 inline bool try_dequeue_from_producer(const producer_token_t &producer, U &item) {
1351 return static_cast<ExplicitProducer *>(producer.producer)->dequeue(item);
1352 }
1353
1354 // Attempts to dequeue several elements from a specific producer's inner queue.
1355 // Returns the number of items actually dequeued.
1356 // If you happen to know which producer you want to dequeue from, this
1357 // is significantly faster than using the general-case try_dequeue methods.
1358 // Returns 0 if the producer's queue appeared empty at the time it
1359 // was checked (so, the queue is likely but not guaranteed to be empty).
1360 // Never allocates. Thread-safe.
1361 template <typename It>
1362 inline size_t try_dequeue_bulk_from_producer(
1363 const producer_token_t &producer, It itemFirst, size_t max) {
1364 return static_cast<ExplicitProducer *>(producer.producer)->dequeue_bulk(itemFirst, max);
1365 }
1366
1367 // Returns an estimate of the total number of elements currently in the queue. This
1368 // estimate is only accurate if the queue has completely stabilized before it is called
1369 // (i.e. all enqueue and dequeue operations have completed and their memory effects are
1370 // visible on the calling thread, and no further operations start while this method is
1371 // being called).
1372 // Thread-safe.
1373 size_t size_approx() const {
1374 size_t size = 0;
1375 for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr;
1376 ptr = ptr->next_prod()) {
1377 size += ptr->size_approx();
1378 }
1379 return size;
1380 }
1381
1382 // Returns true if the underlying atomic variables used by
1383 // the queue are lock-free (they should be on most platforms).
1384 // Thread-safe.
1385 static bool is_lock_free() {
1386 return details::static_is_lock_free<bool>::value == 2
1387 && details::static_is_lock_free<size_t>::value == 2
1388 && details::static_is_lock_free<std::uint32_t>::value == 2
1389 && details::static_is_lock_free<index_t>::value == 2
1390 && details::static_is_lock_free<void *>::value == 2
1391 && details::static_is_lock_free<typename details::thread_id_converter<
1392 details::thread_id_t>::thread_id_numeric_size_t>::value
1393 == 2;
1394 }
1395
1396 private:
1397 friend struct ProducerToken;
1398 friend struct ConsumerToken;
1399 friend struct ExplicitProducer;
1400
1401 friend class ConcurrentQueueTests;
1402
1403 enum AllocationMode { CanAlloc, CannotAlloc };
1404
1405 ///////////////////////////////
1406 // Queue methods
1407 ///////////////////////////////
1408
1409 template <AllocationMode canAlloc, typename U>
1410 inline bool inner_enqueue(const producer_token_t &token, U &&element) {
1411 return static_cast<ExplicitProducer *>(token.producer)
1412 ->ConcurrentQueue::ExplicitProducer::template enqueue<canAlloc>(std::forward<U>(element));
1413 }
1414
1415 template <AllocationMode canAlloc, typename U>
1416 inline bool inner_enqueue(U &&element) {
1417 auto producer = get_or_add_implicit_producer();
1418 return producer == nullptr
1419 ? false
1420 : producer->ConcurrentQueue::ImplicitProducer::template enqueue<canAlloc>(
1421 std::forward<U>(element));
1422 }
1423
1424 template <AllocationMode canAlloc, typename It>
1425 inline bool inner_enqueue_bulk(const producer_token_t &token, It itemFirst, size_t count) {
1426 return static_cast<ExplicitProducer *>(token.producer)
1427 ->ConcurrentQueue::ExplicitProducer::template enqueue_bulk<canAlloc>(itemFirst, count);
1428 }
1429
1430 template <AllocationMode canAlloc, typename It>
1431 inline bool inner_enqueue_bulk(It itemFirst, size_t count) {
1432 auto producer = get_or_add_implicit_producer();
1433 return producer == nullptr
1434 ? false
1435 : producer->ConcurrentQueue::ImplicitProducer::template enqueue_bulk<canAlloc>(
1436 itemFirst, count);
1437 }
1438
1439 inline bool update_current_producer_after_rotation(consumer_token_t &token) {
1440 // Ah, there's been a rotation, figure out where we should be!
1441 auto tail = producerListTail.load(std::memory_order_acquire);
1442 if (token.desiredProducer == nullptr && tail == nullptr) {
1443 return false;
1444 }
1445 auto prodCount = producerCount.load(std::memory_order_relaxed);
1446 auto globalOffset = globalExplicitConsumerOffset.load(std::memory_order_relaxed);
1447 if (details::unlikely(token.desiredProducer == nullptr)) {
1448 // Aha, first time we're dequeueing anything.
1449 // Figure out our local position
1450 // Note: offset is from start, not end, but we're traversing from end -- subtract from count
1451 // first
1452 std::uint32_t offset = prodCount - 1 - (token.initialOffset % prodCount);
1453 token.desiredProducer = tail;
1454 for (std::uint32_t i = 0; i != offset; ++i) {
1455 token.desiredProducer = static_cast<ProducerBase *>(token.desiredProducer)->next_prod();
1456 if (token.desiredProducer == nullptr) {
1457 token.desiredProducer = tail;
1458 }
1459 }
1460 }
1461
1462 std::uint32_t delta = globalOffset - token.lastKnownGlobalOffset;
1463 if (delta >= prodCount) {
1464 delta = delta % prodCount;
1465 }
1466 for (std::uint32_t i = 0; i != delta; ++i) {
1467 token.desiredProducer = static_cast<ProducerBase *>(token.desiredProducer)->next_prod();
1468 if (token.desiredProducer == nullptr) {
1469 token.desiredProducer = tail;
1470 }
1471 }
1472
1473 token.lastKnownGlobalOffset = globalOffset;
1474 token.currentProducer = token.desiredProducer;
1475 token.itemsConsumedFromCurrent = 0;
1476 return true;
1477 }
1478
1479 ///////////////////////////
1480 // Free list
1481 ///////////////////////////
1482
1483 template <typename N>
1484 struct FreeListNode {
1485 FreeListNode() : freeListRefs(0), freeListNext(nullptr) {}
1486
1487 std::atomic<std::uint32_t> freeListRefs;
1488 std::atomic<N *> freeListNext;
1489 };
1490
1491 // A simple CAS-based lock-free free list. Not the fastest thing in the world under heavy
1492 // contention, but simple and correct (assuming nodes are never freed until after the free list is
1493 // destroyed), and fairly speedy under low contention.
1494 template <typename N> // N must inherit FreeListNode or have the same fields (and initialization
1495 // of them)
1496 struct FreeList {
1497 FreeList() : freeListHead(nullptr) {}
1498
1499 FreeList(FreeList &&other) : freeListHead(other.freeListHead.load(std::memory_order_relaxed)) {
1500 other.freeListHead.store(nullptr, std::memory_order_relaxed);
1501 }
1502
1503 void swap(FreeList &other) {
1504 details::swap_relaxed(freeListHead, other.freeListHead);
1505 }
1506
1507 FreeList(const FreeList &) MOODYCAMEL_DELETE_FUNCTION;
1508
1509 FreeList &operator=(const FreeList &) MOODYCAMEL_DELETE_FUNCTION;
1510
1511 inline void add(N *node) {
1512 #if MCDBGQ_NOLOCKFREE_FREELIST
1513 debug::DebugLock lock(mutex);
1514 #endif
1515 // We know that the should-be-on-freelist bit is 0 at this point, so it's safe to
1516 // set it using a fetch_add
1517 if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST, std::memory_order_acq_rel) == 0) {
1518 // Oh look! We were the last ones referencing this node, and we know
1519 // we want to add it to the free list, so let's do it!
1520 add_knowing_refcount_is_zero(node);
1521 }
1522 }
1523
1524 inline N *try_get() {
1525 #if MCDBGQ_NOLOCKFREE_FREELIST
1526 debug::DebugLock lock(mutex);
1527 #endif
1528 auto head = freeListHead.load(std::memory_order_acquire);
1529 while (head != nullptr) {
1530 auto prevHead = head;
1531 auto refs = head->freeListRefs.load(std::memory_order_relaxed);
1532 if ((refs & REFS_MASK) == 0
1533 || !head->freeListRefs.compare_exchange_strong(
1534 refs, refs + 1, std::memory_order_acquire, std::memory_order_relaxed)) {
1535 head = freeListHead.load(std::memory_order_acquire);
1536 continue;
1537 }
1538
1539 // Good, reference count has been incremented (it wasn't at zero), which means we can read
1540 // the next and not worry about it changing between now and the time we do the CAS
1541 auto next = head->freeListNext.load(std::memory_order_relaxed);
1542 if (freeListHead.compare_exchange_strong(
1543 head, next, std::memory_order_acquire, std::memory_order_relaxed)) {
1544 // Yay, got the node. This means it was on the list, which means shouldBeOnFreeList must
1545 // be false no matter the refcount (because nobody else knows it's been taken off yet, it
1546 // can't have been put back on).
1547 assert((head->freeListRefs.load(std::memory_order_relaxed) & SHOULD_BE_ON_FREELIST) == 0);
1548
1549 // Decrease refcount twice, once for our ref, and once for the list's ref
1550 head->freeListRefs.fetch_sub(2, std::memory_order_release);
1551 return head;
1552 }
1553
1554 // OK, the head must have changed on us, but we still need to decrease the refcount we
1555 // increased. Note that we don't need to release any memory effects, but we do need to
1556 // ensure that the reference count decrement happens-after the CAS on the head.
1557 refs = prevHead->freeListRefs.fetch_sub(1, std::memory_order_acq_rel);
1558 if (refs == SHOULD_BE_ON_FREELIST + 1) {
1559 add_knowing_refcount_is_zero(prevHead);
1560 }
1561 }
1562
1563 return nullptr;
1564 }
1565
1566 // Useful for traversing the list when there's no contention (e.g. to destroy remaining nodes)
1567 N *head_unsafe() const {
1568 return freeListHead.load(std::memory_order_relaxed);
1569 }
1570
1571 private:
1572 inline void add_knowing_refcount_is_zero(N *node) {
1573 // Since the refcount is zero, and nobody can increase it once it's zero (except us, and we
1574 // run only one copy of this method per node at a time, i.e. the single thread case), then we
1575 // know we can safely change the next pointer of the node; however, once the refcount is back
1576 // above zero, then other threads could increase it (happens under heavy contention, when the
1577 // refcount goes to zero in between a load and a refcount increment of a node in try_get, then
1578 // back up to something non-zero, then the refcount increment is done by the other thread) --
1579 // so, if the CAS to add the node to the actual list fails, decrease the refcount and leave
1580 // the add operation to the next thread who puts the refcount back at zero (which could be us,
1581 // hence the loop).
1582 auto head = freeListHead.load(std::memory_order_relaxed);
1583 while (true) {
1584 node->freeListNext.store(head, std::memory_order_relaxed);
1585 node->freeListRefs.store(1, std::memory_order_release);
1586 if (!freeListHead.compare_exchange_strong(
1587 head, node, std::memory_order_release, std::memory_order_relaxed)) {
1588 // Hmm, the add failed, but we can only try again when the refcount goes back to zero
1589 if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_release)
1590 == 1) {
1591 continue;
1592 }
1593 }
1594 return;
1595 }
1596 }
1597
1598 private:
1599 // Implemented like a stack, but where node order doesn't matter (nodes are inserted out of
1600 // order under contention)
1601 std::atomic<N *> freeListHead;
1602
1603 static const std::uint32_t REFS_MASK = 0x7FFFFFFF;
1604 static const std::uint32_t SHOULD_BE_ON_FREELIST = 0x80000000;
1605
1606 #if MCDBGQ_NOLOCKFREE_FREELIST
1607 debug::DebugMutex mutex;
1608 #endif
1609 };
1610
1611 ///////////////////////////
1612 // Block
1613 ///////////////////////////
1614
1615 enum InnerQueueContext { implicit_context = 0, explicit_context = 1 };
1616
1617 struct Block {
1618 Block()
1619 : next(nullptr),
1620 elementsCompletelyDequeued(0),
1621 freeListRefs(0),
1622 freeListNext(nullptr),
1623 shouldBeOnFreeList(false),
1624 dynamicallyAllocated(true) {
1625 #if MCDBGQ_TRACKMEM
1626 owner = nullptr;
1627 #endif
1628 }
1629
1630 template <InnerQueueContext context>
1631 inline bool is_empty() const {
1632 if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
1633 // Check flags
1634 for (size_t i = 0; i < BLOCK_SIZE; ++i) {
1635 if (!emptyFlags[i].load(std::memory_order_relaxed)) {
1636 return false;
1637 }
1638 }
1639
1640 // Aha, empty; make sure we have all other memory effects that happened before the empty
1641 // flags were set
1642 std::atomic_thread_fence(std::memory_order_acquire);
1643 return true;
1644 } else {
1645 // Check counter
1646 if (elementsCompletelyDequeued.load(std::memory_order_relaxed) == BLOCK_SIZE) {
1647 std::atomic_thread_fence(std::memory_order_acquire);
1648 return true;
1649 }
1650 assert(elementsCompletelyDequeued.load(std::memory_order_relaxed) <= BLOCK_SIZE);
1651 return false;
1652 }
1653 }
1654
1655 // Returns true if the block is now empty (does not apply in explicit context)
1656 template <InnerQueueContext context>
1657 inline bool set_empty(index_t i) {
1658 if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
1659 // Set flag
1660 assert(!emptyFlags[BLOCK_SIZE - 1
1661 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1))]
1662 .load(std::memory_order_relaxed));
1663 emptyFlags[BLOCK_SIZE - 1 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1))]
1664 .store(true, std::memory_order_release);
1665 return false;
1666 } else {
1667 // Increment counter
1668 auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_release);
1669 assert(prevVal < BLOCK_SIZE);
1670 return prevVal == BLOCK_SIZE - 1;
1671 }
1672 }
1673
1674 // Sets multiple contiguous item statuses to 'empty' (assumes no wrapping and count > 0).
1675 // Returns true if the block is now empty (does not apply in explicit context).
1676 template <InnerQueueContext context>
1677 inline bool set_many_empty(index_t i, size_t count) {
1678 if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
1679 // Set flags
1680 std::atomic_thread_fence(std::memory_order_release);
1681 i = BLOCK_SIZE - 1 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1)) - count
1682 + 1;
1683 for (size_t j = 0; j != count; ++j) {
1684 assert(!emptyFlags[i + j].load(std::memory_order_relaxed));
1685 emptyFlags[i + j].store(true, std::memory_order_relaxed);
1686 }
1687 return false;
1688 } else {
1689 // Increment counter
1690 auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_release);
1691 assert(prevVal + count <= BLOCK_SIZE);
1692 return prevVal + count == BLOCK_SIZE;
1693 }
1694 }
1695
1696 template <InnerQueueContext context>
1697 inline void set_all_empty() {
1698 if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
1699 // Set all flags
1700 for (size_t i = 0; i != BLOCK_SIZE; ++i) {
1701 emptyFlags[i].store(true, std::memory_order_relaxed);
1702 }
1703 } else {
1704 // Reset counter
1705 elementsCompletelyDequeued.store(BLOCK_SIZE, std::memory_order_relaxed);
1706 }
1707 }
1708
1709 template <InnerQueueContext context>
1710 inline void reset_empty() {
1711 if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
1712 // Reset flags
1713 for (size_t i = 0; i != BLOCK_SIZE; ++i) {
1714 emptyFlags[i].store(false, std::memory_order_relaxed);
1715 }
1716 } else {
1717 // Reset counter
1718 elementsCompletelyDequeued.store(0, std::memory_order_relaxed);
1719 }
1720 }
1721
1722 inline T *operator[](index_t idx) MOODYCAMEL_NOEXCEPT {
1723 return static_cast<T *>(static_cast<void *>(elements))
1724 + static_cast<size_t>(idx & static_cast<index_t>(BLOCK_SIZE - 1));
1725 }
1726
1727 inline const T *operator[](index_t idx) const MOODYCAMEL_NOEXCEPT {
1728 return static_cast<const T *>(static_cast<const void *>(elements))
1729 + static_cast<size_t>(idx & static_cast<index_t>(BLOCK_SIZE - 1));
1730 }
1731
1732 private:
1733 // IMPORTANT: This must be the first member in Block, so that if T depends on the alignment of
1734 // addresses returned by malloc, that alignment will be preserved. Apparently clang actually
1735 // generates code that uses this assumption for AVX instructions in some cases. Ideally, we
1736 // should also align Block to the alignment of T in case it's higher than malloc's 16-byte
1737 // alignment, but this is hard to do in a cross-platform way. Assert for this case:
1738 static_assert(std::alignment_of<T>::value <= std::alignment_of<details::max_align_t>::value,
1739 "The queue does not support super-aligned types at this time");
1740 // Additionally, we need the alignment of Block itself to be a multiple of max_align_t since
1741 // otherwise the appropriate padding will not be added at the end of Block in order to make
1742 // arrays of Blocks all be properly aligned (not just the first one). We use a union to force
1743 // this.
1744 union {
1745 char elements[sizeof(T) * BLOCK_SIZE];
1746 details::max_align_t dummy;
1747 };
1748
1749 public:
1750 Block *next;
1751 std::atomic<size_t> elementsCompletelyDequeued;
1752 std::atomic<bool>
1753 emptyFlags[BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD ? BLOCK_SIZE : 1];
1754
1755 public:
1756 std::atomic<std::uint32_t> freeListRefs;
1757 std::atomic<Block *> freeListNext;
1758 std::atomic<bool> shouldBeOnFreeList;
1759 bool dynamicallyAllocated; // Perhaps a better name for this would be
1760 // 'isNotPartOfInitialBlockPool'
1761
1762 #if MCDBGQ_TRACKMEM
1763 void *owner;
1764 #endif
1765 };
1766
1767 static_assert(std::alignment_of<Block>::value >= std::alignment_of<details::max_align_t>::value,
1768 "Internal error: Blocks must be at least as aligned as the type they are wrapping");
1769
1770 #if MCDBGQ_TRACKMEM
1771 public:
1772 struct MemStats;
1773
1774 private:
1775 #endif
1776
1777 ///////////////////////////
1778 // Producer base
1779 ///////////////////////////
1780
1781 struct ProducerBase : public details::ConcurrentQueueProducerTypelessBase {
1782 ProducerBase(ConcurrentQueue *parent_, bool isExplicit_)
1783 : tailIndex(0),
1784 headIndex(0),
1785 dequeueOptimisticCount(0),
1786 dequeueOvercommit(0),
1787 tailBlock(nullptr),
1788 isExplicit(isExplicit_),
1789 parent(parent_) {}
1790
1791 virtual ~ProducerBase() {};
1792
1793 template <typename U>
1794 inline bool dequeue(U &element) {
1795 if (isExplicit) {
1796 return static_cast<ExplicitProducer *>(this)->dequeue(element);
1797 } else {
1798 return static_cast<ImplicitProducer *>(this)->dequeue(element);
1799 }
1800 }
1801
1802 template <typename It>
1803 inline size_t dequeue_bulk(It &itemFirst, size_t max) {
1804 if (isExplicit) {
1805 return static_cast<ExplicitProducer *>(this)->dequeue_bulk(itemFirst, max);
1806 } else {
1807 return static_cast<ImplicitProducer *>(this)->dequeue_bulk(itemFirst, max);
1808 }
1809 }
1810
1811 inline ProducerBase *next_prod() const {
1812 return static_cast<ProducerBase *>(next);
1813 }
1814
1815 inline size_t size_approx() const {
1816 auto tail = tailIndex.load(std::memory_order_relaxed);
1817 auto head = headIndex.load(std::memory_order_relaxed);
1818 return details::circular_less_than(head, tail) ? static_cast<size_t>(tail - head) : 0;
1819 }
1820
1821 inline index_t getTail() const {
1822 return tailIndex.load(std::memory_order_relaxed);
1823 }
1824
1825 protected:
1826 std::atomic<index_t> tailIndex; // Where to enqueue to next
1827 std::atomic<index_t> headIndex; // Where to dequeue from next
1828
1829 std::atomic<index_t> dequeueOptimisticCount;
1830 std::atomic<index_t> dequeueOvercommit;
1831
1832 Block *tailBlock;
1833
1834 public:
1835 bool isExplicit;
1836 ConcurrentQueue *parent;
1837
1838 protected:
1839 #if MCDBGQ_TRACKMEM
1840 friend struct MemStats;
1841 #endif
1842 };
1843
1844 ///////////////////////////
1845 // Explicit queue
1846 ///////////////////////////
1847
1848 struct ExplicitProducer : public ProducerBase {
1849 explicit ExplicitProducer(ConcurrentQueue *parent)
1850 : ProducerBase(parent, true),
1851 blockIndex(nullptr),
1852 pr_blockIndexSlotsUsed(0),
1853 pr_blockIndexSize(EXPLICIT_INITIAL_INDEX_SIZE >> 1),
1854 pr_blockIndexFront(0),
1855 pr_blockIndexEntries(nullptr),
1856 pr_blockIndexRaw(nullptr) {
1857 size_t poolBasedIndexSize = details::ceil_to_pow_2(parent->initialBlockPoolSize) >> 1;
1858 if (poolBasedIndexSize > pr_blockIndexSize) {
1859 pr_blockIndexSize = poolBasedIndexSize;
1860 }
1861
1862 new_block_index(0); // This creates an index with double the number of current entries, i.e.
1863 // EXPLICIT_INITIAL_INDEX_SIZE
1864 }
1865
1866 ~ExplicitProducer() {
1867 // Destruct any elements not yet dequeued.
1868 // Since we're in the destructor, we can assume all elements
1869 // are either completely dequeued or completely not (no halfways).
1870 if (this->tailBlock != nullptr) { // Note this means there must be a block index too
1871 // First find the block that's partially dequeued, if any
1872 Block *halfDequeuedBlock = nullptr;
1873 if ((this->headIndex.load(std::memory_order_relaxed) & static_cast<index_t>(BLOCK_SIZE - 1))
1874 != 0) {
1875 // The head's not on a block boundary, meaning a block somewhere is partially dequeued
1876 // (or the head block is the tail block and was fully dequeued, but the head/tail are
1877 // still not on a boundary)
1878 size_t i = (pr_blockIndexFront - pr_blockIndexSlotsUsed) & (pr_blockIndexSize - 1);
1879 while (details::circular_less_than<index_t>(pr_blockIndexEntries[i].base + BLOCK_SIZE,
1880 this->headIndex.load(std::memory_order_relaxed))) {
1881 i = (i + 1) & (pr_blockIndexSize - 1);
1882 }
1883 assert(details::circular_less_than<index_t>(
1884 pr_blockIndexEntries[i].base, this->headIndex.load(std::memory_order_relaxed)));
1885 halfDequeuedBlock = pr_blockIndexEntries[i].block;
1886 }
1887
1888 // Start at the head block (note the first line in the loop gives us the head from the tail
1889 // on the first iteration)
1890 auto block = this->tailBlock;
1891 do {
1892 block = block->next;
1893 if (block->template is_empty<explicit_context>()) {
1894 continue;
1895 }
1896
1897 size_t i = 0; // Offset into block
1898 if (block == halfDequeuedBlock) {
1899 i = static_cast<size_t>(this->headIndex.load(std::memory_order_relaxed)
1900 & static_cast<index_t>(BLOCK_SIZE - 1));
1901 }
1902
1903 // Walk through all the items in the block; if this is the tail block, we need to stop
1904 // when we reach the tail index
1905 auto lastValidIndex
1906 = (this->tailIndex.load(std::memory_order_relaxed)
1907 & static_cast<index_t>(BLOCK_SIZE - 1))
1908 == 0
1909 ? BLOCK_SIZE
1910 : static_cast<size_t>(this->tailIndex.load(std::memory_order_relaxed)
1911 & static_cast<index_t>(BLOCK_SIZE - 1));
1912 while (i != BLOCK_SIZE && (block != this->tailBlock || i != lastValidIndex)) {
1913 (*block)[i++]->~T();
1914 }
1915 } while (block != this->tailBlock);
1916 }
1917
1918 // Destroy all blocks that we own
1919 if (this->tailBlock != nullptr) {
1920 auto block = this->tailBlock;
1921 do {
1922 auto nextBlock = block->next;
1923 if (block->dynamicallyAllocated) {
1924 destroy(block);
1925 } else {
1926 this->parent->add_block_to_free_list(block);
1927 }
1928 block = nextBlock;
1929 } while (block != this->tailBlock);
1930 }
1931
1932 // Destroy the block indices
1933 auto header = static_cast<BlockIndexHeader *>(pr_blockIndexRaw);
1934 while (header != nullptr) {
1935 auto prev = static_cast<BlockIndexHeader *>(header->prev);
1936 header->~BlockIndexHeader();
1937 (Traits::free)(header);
1938 header = prev;
1939 }
1940 }
1941
1942 template <AllocationMode allocMode, typename U>
1943 inline bool enqueue(U &&element) {
1944 index_t currentTailIndex = this->tailIndex.load(std::memory_order_relaxed);
1945 index_t newTailIndex = 1 + currentTailIndex;
1946 if ((currentTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
1947 // We reached the end of a block, start a new one
1948 auto startBlock = this->tailBlock;
1949 auto originalBlockIndexSlotsUsed = pr_blockIndexSlotsUsed;
1950 if (this->tailBlock != nullptr
1951 && this->tailBlock->next->template is_empty<explicit_context>()) {
1952 // We can re-use the block ahead of us, it's empty!
1953 this->tailBlock = this->tailBlock->next;
1954 this->tailBlock->template reset_empty<explicit_context>();
1955
1956 // We'll put the block on the block index (guaranteed to be room since we're conceptually
1957 // removing the last block from it first -- except instead of removing then adding, we can
1958 // just overwrite). Note that there must be a valid block index here, since even if
1959 // allocation failed in the ctor, it would have been re-attempted when adding the first
1960 // block to the queue; since there is such a block, a block index must have been
1961 // successfully allocated.
1962 } else {
1963 // Whatever head value we see here is >= the last value we saw here (relatively),
1964 // and <= its current value. Since we have the most recent tail, the head must be
1965 // <= to it.
1966 auto head = this->headIndex.load(std::memory_order_relaxed);
1967 assert(!details::circular_less_than<index_t>(currentTailIndex, head));
1968 if (!details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE)
1969 || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value
1970 && (MAX_SUBQUEUE_SIZE == 0
1971 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head))) {
1972 // We can't enqueue in another block because there's not enough leeway -- the
1973 // tail could surpass the head by the time the block fills up! (Or we'll exceed
1974 // the size limit, if the second part of the condition was true.)
1975 return false;
1976 }
1977 // We're going to need a new block; check that the block index has room
1978 if (pr_blockIndexRaw == nullptr || pr_blockIndexSlotsUsed == pr_blockIndexSize) {
1979 // Hmm, the circular block index is already full -- we'll need
1980 // to allocate a new index. Note pr_blockIndexRaw can only be nullptr if
1981 // the initial allocation failed in the constructor.
1982
1983 if (allocMode == CannotAlloc || !new_block_index(pr_blockIndexSlotsUsed)) {
1984 return false;
1985 }
1986 }
1987
1988 // Insert a new block in the circular linked list
1989 auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
1990 if (newBlock == nullptr) {
1991 return false;
1992 }
1993 #if MCDBGQ_TRACKMEM
1994 newBlock->owner = this;
1995 #endif
1996 newBlock->template reset_empty<explicit_context>();
1997 if (this->tailBlock == nullptr) {
1998 newBlock->next = newBlock;
1999 } else {
2000 newBlock->next = this->tailBlock->next;
2001 this->tailBlock->next = newBlock;
2002 }
2003 this->tailBlock = newBlock;
2004 ++pr_blockIndexSlotsUsed;
2005 }
2006
2007 if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
2008 // The constructor may throw. We want the element not to appear in the queue in
2009 // that case (without corrupting the queue):
2010 MOODYCAMEL_TRY {
2011 new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
2012 }
2013 MOODYCAMEL_CATCH(...) {
2014 // Revert change to the current block, but leave the new block available
2015 // for next time
2016 pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
2017 this->tailBlock = startBlock == nullptr ? this->tailBlock : startBlock;
2018 MOODYCAMEL_RETHROW;
2019 }
2020 } else {
2021 (void)startBlock;
2022 (void)originalBlockIndexSlotsUsed;
2023 }
2024
2025 // Add block to block index
2026 auto &entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
2027 entry.base = currentTailIndex;
2028 entry.block = this->tailBlock;
2029 blockIndex.load(std::memory_order_relaxed)
2030 ->front.store(pr_blockIndexFront, std::memory_order_release);
2031 pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
2032
2033 if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
2034 this->tailIndex.store(newTailIndex, std::memory_order_release);
2035 return true;
2036 }
2037 }
2038
2039 // Enqueue
2040 new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
2041
2042 this->tailIndex.store(newTailIndex, std::memory_order_release);
2043 return true;
2044 }
2045
2046 template <typename U>
2047 bool dequeue(U &element) {
2048 auto tail = this->tailIndex.load(std::memory_order_relaxed);
2049 auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
2050 if (details::circular_less_than<index_t>(
2051 this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit, tail)) {
2052 // Might be something to dequeue, let's give it a try
2053
2054 // Note that this if is purely for performance purposes in the common case when the queue is
2055 // empty and the values are eventually consistent -- we may enter here spuriously.
2056
2057 // Note that whatever the values of overcommit and tail are, they are not going to change
2058 // (unless we change them) and must be the same value at this point (inside the if) as when
2059 // the if condition was evaluated.
2060
2061 // We insert an acquire fence here to synchronize-with the release upon incrementing
2062 // dequeueOvercommit below. This ensures that whatever the value we got loaded into
2063 // overcommit, the load of dequeueOptisticCount in the fetch_add below will result in a
2064 // value at least as recent as that (and therefore at least as large). Note that I believe a
2065 // compiler (signal) fence here would be sufficient due to the nature of fetch_add (all
2066 // read-modify-write operations are guaranteed to work on the latest value in the
2067 // modification order), but unfortunately that can't be shown to be correct using only the
2068 // C++11 standard. See
2069 // http://stackoverflow.com/questions/18223161/what-are-the-c11-memory-ordering-guarantees-in-this-corner-case
2070 std::atomic_thread_fence(std::memory_order_acquire);
2071
2072 // Increment optimistic counter, then check if it went over the boundary
2073 auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(1, std::memory_order_relaxed);
2074
2075 // Note that since dequeueOvercommit must be <= dequeueOptimisticCount (because
2076 // dequeueOvercommit is only ever incremented after dequeueOptimisticCount -- this is
2077 // enforced in the `else` block below), and since we now have a version of
2078 // dequeueOptimisticCount that is at least as recent as overcommit (due to the release upon
2079 // incrementing dequeueOvercommit and the acquire above that synchronizes with it),
2080 // overcommit <= myDequeueCount.
2081 assert(overcommit <= myDequeueCount);
2082
2083 // Note that we reload tail here in case it changed; it will be the same value as before or
2084 // greater, since this load is sequenced after (happens after) the earlier load above. This
2085 // is supported by read-read coherency (as defined in the standard), explained here:
2086 // http://en.cppreference.com/w/cpp/atomic/memory_order
2087 tail = this->tailIndex.load(std::memory_order_acquire);
2088 if (details::likely(
2089 details::circular_less_than<index_t>(myDequeueCount - overcommit, tail))) {
2090 // Guaranteed to be at least one element to dequeue!
2091
2092 // Get the index. Note that since there's guaranteed to be at least one element, this
2093 // will never exceed tail. We need to do an acquire-release fence here since it's possible
2094 // that whatever condition got us to this point was for an earlier enqueued element (that
2095 // we already see the memory effects for), but that by the time we increment somebody else
2096 // has incremented it, and we need to see the memory effects for *that* element, which is
2097 // in such a case is necessarily visible on the thread that incremented it in the first
2098 // place with the more current condition (they must have acquired a tail that is at least
2099 // as recent).
2100 auto index = this->headIndex.fetch_add(1, std::memory_order_acq_rel);
2101
2102 // Determine which block the element is in
2103
2104 auto localBlockIndex = blockIndex.load(std::memory_order_acquire);
2105 auto localBlockIndexHead = localBlockIndex->front.load(std::memory_order_acquire);
2106
2107 // We need to be careful here about subtracting and dividing because of index wrap-around.
2108 // When an index wraps, we need to preserve the sign of the offset when dividing it by the
2109 // block size (in order to get a correct signed block count offset in all cases):
2110 auto headBase = localBlockIndex->entries[localBlockIndexHead].base;
2111 auto blockBaseIndex = index & ~static_cast<index_t>(BLOCK_SIZE - 1);
2112 auto offset = static_cast<size_t>(
2113 static_cast<typename std::make_signed<index_t>::type>(blockBaseIndex - headBase)
2114 / BLOCK_SIZE);
2115 auto block = localBlockIndex
2116 ->entries[(localBlockIndexHead + offset) & (localBlockIndex->size - 1)]
2117 .block;
2118
2119 // Dequeue
2120 auto &el = *((*block)[index]);
2121 if (!MOODYCAMEL_NOEXCEPT_ASSIGN(T, T &&, element = std::move(el))) {
2122 // Make sure the element is still fully dequeued and destroyed even if the assignment
2123 // throws
2124 struct Guard {
2125 Block *block;
2126 index_t index;
2127
2128 ~Guard() {
2129 (*block)[index]->~T();
2130 block->template set_empty<explicit_context>(index);
2131 }
2132 } guard = {block, index};
2133
2134 element = std::move(el);
2135 } else {
2136 element = std::move(el);
2137 el.~T();
2138 block->template set_empty<explicit_context>(index);
2139 }
2140
2141 return true;
2142 } else {
2143 // Wasn't anything to dequeue after all; make the effective dequeue count eventually
2144 // consistent
2145 this->dequeueOvercommit.fetch_add(1,
2146 std::memory_order_release); // Release so that the fetch_add on
2147 // dequeueOptimisticCount is guaranteed to happen before
2148 // this write
2149 }
2150 }
2151
2152 return false;
2153 }
2154
2155 template <AllocationMode allocMode, typename It>
2156 bool enqueue_bulk(It itemFirst, size_t count) {
2157 // First, we need to make sure we have enough room to enqueue all of the elements;
2158 // this means pre-allocating blocks and putting them in the block index (but only if
2159 // all the allocations succeeded).
2160 index_t startTailIndex = this->tailIndex.load(std::memory_order_relaxed);
2161 auto startBlock = this->tailBlock;
2162 auto originalBlockIndexFront = pr_blockIndexFront;
2163 auto originalBlockIndexSlotsUsed = pr_blockIndexSlotsUsed;
2164
2165 Block *firstAllocatedBlock = nullptr;
2166
2167 // Figure out how many blocks we'll need to allocate, and do so
2168 size_t blockBaseDiff = ((startTailIndex + count - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1))
2169 - ((startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1));
2170 index_t currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
2171 if (blockBaseDiff > 0) {
2172 // Allocate as many blocks as possible from ahead
2173 while (blockBaseDiff > 0 && this->tailBlock != nullptr
2174 && this->tailBlock->next != firstAllocatedBlock
2175 && this->tailBlock->next->template is_empty<explicit_context>()) {
2176 blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
2177 currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
2178
2179 this->tailBlock = this->tailBlock->next;
2180 firstAllocatedBlock
2181 = firstAllocatedBlock == nullptr ? this->tailBlock : firstAllocatedBlock;
2182
2183 auto &entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
2184 entry.base = currentTailIndex;
2185 entry.block = this->tailBlock;
2186 pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
2187 }
2188
2189 // Now allocate as many blocks as necessary from the block pool
2190 while (blockBaseDiff > 0) {
2191 blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
2192 currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
2193
2194 auto head = this->headIndex.load(std::memory_order_relaxed);
2195 assert(!details::circular_less_than<index_t>(currentTailIndex, head));
2196 bool full = !details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE)
2197 || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value
2198 && (MAX_SUBQUEUE_SIZE == 0
2199 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head));
2200 if (pr_blockIndexRaw == nullptr || pr_blockIndexSlotsUsed == pr_blockIndexSize || full) {
2201 if (allocMode == CannotAlloc || full || !new_block_index(originalBlockIndexSlotsUsed)) {
2202 // Failed to allocate, undo changes (but keep injected blocks)
2203 pr_blockIndexFront = originalBlockIndexFront;
2204 pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
2205 this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
2206 return false;
2207 }
2208
2209 // pr_blockIndexFront is updated inside new_block_index, so we need to
2210 // update our fallback value too (since we keep the new index even if we
2211 // later fail)
2212 originalBlockIndexFront = originalBlockIndexSlotsUsed;
2213 }
2214
2215 // Insert a new block in the circular linked list
2216 auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
2217 if (newBlock == nullptr) {
2218 pr_blockIndexFront = originalBlockIndexFront;
2219 pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
2220 this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
2221 return false;
2222 }
2223
2224 #if MCDBGQ_TRACKMEM
2225 newBlock->owner = this;
2226 #endif
2227 newBlock->template set_all_empty<explicit_context>();
2228 if (this->tailBlock == nullptr) {
2229 newBlock->next = newBlock;
2230 } else {
2231 newBlock->next = this->tailBlock->next;
2232 this->tailBlock->next = newBlock;
2233 }
2234 this->tailBlock = newBlock;
2235 firstAllocatedBlock
2236 = firstAllocatedBlock == nullptr ? this->tailBlock : firstAllocatedBlock;
2237
2238 ++pr_blockIndexSlotsUsed;
2239
2240 auto &entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
2241 entry.base = currentTailIndex;
2242 entry.block = this->tailBlock;
2243 pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
2244 }
2245
2246 // Excellent, all allocations succeeded. Reset each block's emptiness before we fill them
2247 // up, and publish the new block index front
2248 auto block = firstAllocatedBlock;
2249 while (true) {
2250 block->template reset_empty<explicit_context>();
2251 if (block == this->tailBlock) {
2252 break;
2253 }
2254 block = block->next;
2255 }
2256
2257 if (MOODYCAMEL_NOEXCEPT_CTOR(
2258 T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
2259 blockIndex.load(std::memory_order_relaxed)
2260 ->front.store(
2261 (pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release);
2262 }
2263 }
2264
2265 // Enqueue, one block at a time
2266 index_t newTailIndex = startTailIndex + static_cast<index_t>(count);
2267 currentTailIndex = startTailIndex;
2268 auto endBlock = this->tailBlock;
2269 this->tailBlock = startBlock;
2270 assert((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0
2271 || firstAllocatedBlock != nullptr || count == 0);
2272 if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0
2273 && firstAllocatedBlock != nullptr) {
2274 this->tailBlock = firstAllocatedBlock;
2275 }
2276 while (true) {
2277 auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1))
2278 + static_cast<index_t>(BLOCK_SIZE);
2279 if (details::circular_less_than<index_t>(newTailIndex, stopIndex)) {
2280 stopIndex = newTailIndex;
2281 }
2282 if (MOODYCAMEL_NOEXCEPT_CTOR(
2283 T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
2284 while (currentTailIndex != stopIndex) {
2285 new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++);
2286 }
2287 } else {
2288 MOODYCAMEL_TRY {
2289 while (currentTailIndex != stopIndex) {
2290 // Must use copy constructor even if move constructor is available
2291 // because we may have to revert if there's an exception.
2292 // Sorry about the horrible templated next line, but it was the only way
2293 // to disable moving *at compile time*, which is important because a type
2294 // may only define a (noexcept) move constructor, and so calls to the
2295 // cctor will not compile, even if they are in an if branch that will never
2296 // be executed
2297 new ((*this->tailBlock)[currentTailIndex])
2298 T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst),
2299 new (nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst));
2300 ++currentTailIndex;
2301 ++itemFirst;
2302 }
2303 }
2304 MOODYCAMEL_CATCH(...) {
2305 // Oh dear, an exception's been thrown -- destroy the elements that
2306 // were enqueued so far and revert the entire bulk operation (we'll keep
2307 // any allocated blocks in our linked list for later, though).
2308 auto constructedStopIndex = currentTailIndex;
2309 auto lastBlockEnqueued = this->tailBlock;
2310
2311 pr_blockIndexFront = originalBlockIndexFront;
2312 pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
2313 this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
2314
2315 if (!details::is_trivially_destructible<T>::value) {
2316 auto block = startBlock;
2317 if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
2318 block = firstAllocatedBlock;
2319 }
2320 currentTailIndex = startTailIndex;
2321 while (true) {
2322 stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1))
2323 + static_cast<index_t>(BLOCK_SIZE);
2324 if (details::circular_less_than<index_t>(constructedStopIndex, stopIndex)) {
2325 stopIndex = constructedStopIndex;
2326 }
2327 while (currentTailIndex != stopIndex) {
2328 (*block)[currentTailIndex++]->~T();
2329 }
2330 if (block == lastBlockEnqueued) {
2331 break;
2332 }
2333 block = block->next;
2334 }
2335 }
2336 MOODYCAMEL_RETHROW;
2337 }
2338 }
2339
2340 if (this->tailBlock == endBlock) {
2341 assert(currentTailIndex == newTailIndex);
2342 break;
2343 }
2344 this->tailBlock = this->tailBlock->next;
2345 }
2346
2347 if (!MOODYCAMEL_NOEXCEPT_CTOR(
2348 T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))
2349 && firstAllocatedBlock != nullptr) {
2350 blockIndex.load(std::memory_order_relaxed)
2351 ->front.store(
2352 (pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release);
2353 }
2354
2355 this->tailIndex.store(newTailIndex, std::memory_order_release);
2356 return true;
2357 }
2358
2359 template <typename It>
2360 size_t dequeue_bulk(It &itemFirst, size_t max) {
2361 auto tail = this->tailIndex.load(std::memory_order_relaxed);
2362 auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
2363 auto desiredCount = static_cast<size_t>(
2364 tail - (this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit));
2365 if (details::circular_less_than<size_t>(0, desiredCount)) {
2366 desiredCount = desiredCount < max ? desiredCount : max;
2367 std::atomic_thread_fence(std::memory_order_acquire);
2368
2369 auto myDequeueCount
2370 = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed);
2371 assert(overcommit <= myDequeueCount);
2372
2373 tail = this->tailIndex.load(std::memory_order_acquire);
2374 auto actualCount = static_cast<size_t>(tail - (myDequeueCount - overcommit));
2375 if (details::circular_less_than<size_t>(0, actualCount)) {
2376 actualCount = desiredCount < actualCount ? desiredCount : actualCount;
2377 if (actualCount < desiredCount) {
2378 this->dequeueOvercommit.fetch_add(
2379 desiredCount - actualCount, std::memory_order_release);
2380 }
2381
2382 // Get the first index. Note that since there's guaranteed to be at least actualCount
2383 // elements, this will never exceed tail.
2384 auto firstIndex = this->headIndex.fetch_add(actualCount, std::memory_order_acq_rel);
2385
2386 // Determine which block the first element is in
2387 auto localBlockIndex = blockIndex.load(std::memory_order_acquire);
2388 auto localBlockIndexHead = localBlockIndex->front.load(std::memory_order_acquire);
2389
2390 auto headBase = localBlockIndex->entries[localBlockIndexHead].base;
2391 auto firstBlockBaseIndex = firstIndex & ~static_cast<index_t>(BLOCK_SIZE - 1);
2392 auto offset = static_cast<size_t>(
2393 static_cast<typename std::make_signed<index_t>::type>(firstBlockBaseIndex - headBase)
2394 / BLOCK_SIZE);
2395 auto indexIndex = (localBlockIndexHead + offset) & (localBlockIndex->size - 1);
2396
2397 // Iterate the blocks and dequeue
2398 auto index = firstIndex;
2399 do {
2400 auto firstIndexInBlock = index;
2401 auto endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1))
2402 + static_cast<index_t>(BLOCK_SIZE);
2403 endIndex = details::circular_less_than<index_t>(
2404 firstIndex + static_cast<index_t>(actualCount), endIndex)
2405 ? firstIndex + static_cast<index_t>(actualCount)
2406 : endIndex;
2407 auto block = localBlockIndex->entries[indexIndex].block;
2408 if (MOODYCAMEL_NOEXCEPT_ASSIGN(
2409 T, T &&, details::deref_noexcept(itemFirst) = std::move((*(*block)[index])))) {
2410 while (index != endIndex) {
2411 auto &el = *((*block)[index]);
2412 *itemFirst++ = std::move(el);
2413 el.~T();
2414 ++index;
2415 }
2416 } else {
2417 MOODYCAMEL_TRY {
2418 while (index != endIndex) {
2419 auto &el = *((*block)[index]);
2420 *itemFirst = std::move(el);
2421 ++itemFirst;
2422 el.~T();
2423 ++index;
2424 }
2425 }
2426 MOODYCAMEL_CATCH(...) {
2427 // It's too late to revert the dequeue, but we can make sure that all
2428 // the dequeued objects are properly destroyed and the block index
2429 // (and empty count) are properly updated before we propagate the exception
2430 do {
2431 block = localBlockIndex->entries[indexIndex].block;
2432 while (index != endIndex) {
2433 (*block)[index++]->~T();
2434 }
2435 block->template set_many_empty<explicit_context>(
2436 firstIndexInBlock, static_cast<size_t>(endIndex - firstIndexInBlock));
2437 indexIndex = (indexIndex + 1) & (localBlockIndex->size - 1);
2438
2439 firstIndexInBlock = index;
2440 endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1))
2441 + static_cast<index_t>(BLOCK_SIZE);
2442 endIndex = details::circular_less_than<index_t>(
2443 firstIndex + static_cast<index_t>(actualCount), endIndex)
2444 ? firstIndex + static_cast<index_t>(actualCount)
2445 : endIndex;
2446 } while (index != firstIndex + actualCount);
2447
2448 MOODYCAMEL_RETHROW;
2449 }
2450 }
2451 block->template set_many_empty<explicit_context>(
2452 firstIndexInBlock, static_cast<size_t>(endIndex - firstIndexInBlock));
2453 indexIndex = (indexIndex + 1) & (localBlockIndex->size - 1);
2454 } while (index != firstIndex + actualCount);
2455
2456 return actualCount;
2457 } else {
2458 // Wasn't anything to dequeue after all; make the effective dequeue count eventually
2459 // consistent
2460 this->dequeueOvercommit.fetch_add(desiredCount, std::memory_order_release);
2461 }
2462 }
2463
2464 return 0;
2465 }
2466
2467 private:
2468 struct BlockIndexEntry {
2469 index_t base;
2470 Block *block;
2471 };
2472
2473 struct BlockIndexHeader {
2474 size_t size;
2475 std::atomic<size_t> front; // Current slot (not next, like pr_blockIndexFront)
2476 BlockIndexEntry *entries;
2477 void *prev;
2478 };
2479
2480 bool new_block_index(size_t numberOfFilledSlotsToExpose) {
2481 auto prevBlockSizeMask = pr_blockIndexSize - 1;
2482
2483 // Create the new block
2484 pr_blockIndexSize <<= 1;
2485 auto newRawPtr = static_cast<char *>(
2486 (Traits::malloc)(sizeof(BlockIndexHeader) + std::alignment_of<BlockIndexEntry>::value - 1
2487 + sizeof(BlockIndexEntry) * pr_blockIndexSize));
2488 if (newRawPtr == nullptr) {
2489 pr_blockIndexSize >>= 1; // Reset to allow graceful retry
2490 return false;
2491 }
2492
2493 auto newBlockIndexEntries = reinterpret_cast<BlockIndexEntry *>(
2494 details::align_for<BlockIndexEntry>(newRawPtr + sizeof(BlockIndexHeader)));
2495
2496 // Copy in all the old indices, if any
2497 size_t j = 0;
2498 if (pr_blockIndexSlotsUsed != 0) {
2499 auto i = (pr_blockIndexFront - pr_blockIndexSlotsUsed) & prevBlockSizeMask;
2500 do {
2501 newBlockIndexEntries[j++] = pr_blockIndexEntries[i];
2502 i = (i + 1) & prevBlockSizeMask;
2503 } while (i != pr_blockIndexFront);
2504 }
2505
2506 // Update everything
2507 auto header = new (newRawPtr) BlockIndexHeader;
2508 header->size = pr_blockIndexSize;
2509 header->front.store(numberOfFilledSlotsToExpose - 1, std::memory_order_relaxed);
2510 header->entries = newBlockIndexEntries;
2511 header->prev
2512 = pr_blockIndexRaw; // we link the new block to the old one so we can free it later
2513
2514 pr_blockIndexFront = j;
2515 pr_blockIndexEntries = newBlockIndexEntries;
2516 pr_blockIndexRaw = newRawPtr;
2517 blockIndex.store(header, std::memory_order_release);
2518
2519 return true;
2520 }
2521
2522 private:
2523 std::atomic<BlockIndexHeader *> blockIndex;
2524
2525 // To be used by producer only -- consumer must use the ones in referenced by blockIndex
2526 size_t pr_blockIndexSlotsUsed;
2527 size_t pr_blockIndexSize;
2528 size_t pr_blockIndexFront; // Next slot (not current)
2529 BlockIndexEntry *pr_blockIndexEntries;
2530 void *pr_blockIndexRaw;
2531
2532 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
2533 public:
2534 ExplicitProducer *nextExplicitProducer;
2535
2536 private:
2537 #endif
2538
2539 #if MCDBGQ_TRACKMEM
2540 friend struct MemStats;
2541 #endif
2542 };
2543
2544 //////////////////////////////////
2545 // Implicit queue
2546 //////////////////////////////////
2547
2548 struct ImplicitProducer : public ProducerBase {
2549 ImplicitProducer(ConcurrentQueue *parent)
2550 : ProducerBase(parent, false),
2551 nextBlockIndexCapacity(IMPLICIT_INITIAL_INDEX_SIZE),
2552 blockIndex(nullptr) {
2553 new_block_index();
2554 }
2555
2556 ~ImplicitProducer() {
2557 // Note that since we're in the destructor we can assume that all enqueue/dequeue operations
2558 // completed already; this means that all undequeued elements are placed contiguously across
2559 // contiguous blocks, and that only the first and last remaining blocks can be only partially
2560 // empty (all other remaining blocks must be completely full).
2561
2562 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
2563 // Unregister ourselves for thread termination notification
2564 if (!this->inactive.load(std::memory_order_relaxed)) {
2565 details::ThreadExitNotifier::unsubscribe(&threadExitListener);
2566 }
2567 #endif
2568
2569 // Destroy all remaining elements!
2570 auto tail = this->tailIndex.load(std::memory_order_relaxed);
2571 auto index = this->headIndex.load(std::memory_order_relaxed);
2572 Block *block = nullptr;
2573 assert(index == tail || details::circular_less_than(index, tail));
2574 bool forceFreeLastBlock
2575 = index != tail; // If we enter the loop, then the last (tail) block will not be freed
2576 while (index != tail) {
2577 if ((index & static_cast<index_t>(BLOCK_SIZE - 1)) == 0 || block == nullptr) {
2578 if (block != nullptr) {
2579 // Free the old block
2580 this->parent->add_block_to_free_list(block);
2581 }
2582
2583 block = get_block_index_entry_for_index(index)->value.load(std::memory_order_relaxed);
2584 }
2585
2586 ((*block)[index])->~T();
2587 ++index;
2588 }
2589 // Even if the queue is empty, there's still one block that's not on the free list
2590 // (unless the head index reached the end of it, in which case the tail will be poised
2591 // to create a new block).
2592 if (this->tailBlock != nullptr
2593 && (forceFreeLastBlock || (tail & static_cast<index_t>(BLOCK_SIZE - 1)) != 0)) {
2594 this->parent->add_block_to_free_list(this->tailBlock);
2595 }
2596
2597 // Destroy block index
2598 auto localBlockIndex = blockIndex.load(std::memory_order_relaxed);
2599 if (localBlockIndex != nullptr) {
2600 for (size_t i = 0; i != localBlockIndex->capacity; ++i) {
2601 localBlockIndex->index[i]->~BlockIndexEntry();
2602 }
2603 do {
2604 auto prev = localBlockIndex->prev;
2605 localBlockIndex->~BlockIndexHeader();
2606 (Traits::free)(localBlockIndex);
2607 localBlockIndex = prev;
2608 } while (localBlockIndex != nullptr);
2609 }
2610 }
2611
2612 template <AllocationMode allocMode, typename U>
2613 inline bool enqueue(U &&element) {
2614 index_t currentTailIndex = this->tailIndex.load(std::memory_order_relaxed);
2615 index_t newTailIndex = 1 + currentTailIndex;
2616 if ((currentTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
2617 // We reached the end of a block, start a new one
2618 auto head = this->headIndex.load(std::memory_order_relaxed);
2619 assert(!details::circular_less_than<index_t>(currentTailIndex, head));
2620 if (!details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE)
2621 || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value
2622 && (MAX_SUBQUEUE_SIZE == 0
2623 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head))) {
2624 return false;
2625 }
2626 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
2627 debug::DebugLock lock(mutex);
2628 #endif
2629 // Find out where we'll be inserting this block in the block index
2630 BlockIndexEntry *idxEntry;
2631 if (!insert_block_index_entry<allocMode>(idxEntry, currentTailIndex)) {
2632 return false;
2633 }
2634
2635 // Get ahold of a new block
2636 auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
2637 if (newBlock == nullptr) {
2638 rewind_block_index_tail();
2639 idxEntry->value.store(nullptr, std::memory_order_relaxed);
2640 return false;
2641 }
2642 #if MCDBGQ_TRACKMEM
2643 newBlock->owner = this;
2644 #endif
2645 newBlock->template reset_empty<implicit_context>();
2646
2647 if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
2648 // May throw, try to insert now before we publish the fact that we have this new block
2649 MOODYCAMEL_TRY {
2650 new ((*newBlock)[currentTailIndex]) T(std::forward<U>(element));
2651 }
2652 MOODYCAMEL_CATCH(...) {
2653 rewind_block_index_tail();
2654 idxEntry->value.store(nullptr, std::memory_order_relaxed);
2655 this->parent->add_block_to_free_list(newBlock);
2656 MOODYCAMEL_RETHROW;
2657 }
2658 }
2659
2660 // Insert the new block into the index
2661 idxEntry->value.store(newBlock, std::memory_order_relaxed);
2662
2663 this->tailBlock = newBlock;
2664
2665 if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
2666 this->tailIndex.store(newTailIndex, std::memory_order_release);
2667 return true;
2668 }
2669 }
2670
2671 // Enqueue
2672 new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
2673
2674 this->tailIndex.store(newTailIndex, std::memory_order_release);
2675 return true;
2676 }
2677
2678 template <typename U>
2679 bool dequeue(U &element) {
2680 // See ExplicitProducer::dequeue for rationale and explanation
2681 index_t tail = this->tailIndex.load(std::memory_order_relaxed);
2682 index_t overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
2683 if (details::circular_less_than<index_t>(
2684 this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit, tail)) {
2685 std::atomic_thread_fence(std::memory_order_acquire);
2686
2687 index_t myDequeueCount
2688 = this->dequeueOptimisticCount.fetch_add(1, std::memory_order_relaxed);
2689 assert(overcommit <= myDequeueCount);
2690 tail = this->tailIndex.load(std::memory_order_acquire);
2691 if (details::likely(
2692 details::circular_less_than<index_t>(myDequeueCount - overcommit, tail))) {
2693 index_t index = this->headIndex.fetch_add(1, std::memory_order_acq_rel);
2694
2695 // Determine which block the element is in
2696 auto entry = get_block_index_entry_for_index(index);
2697
2698 // Dequeue
2699 auto block = entry->value.load(std::memory_order_relaxed);
2700 auto &el = *((*block)[index]);
2701
2702 if (!MOODYCAMEL_NOEXCEPT_ASSIGN(T, T &&, element = std::move(el))) {
2703 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
2704 // Note: Acquiring the mutex with every dequeue instead of only when a block
2705 // is released is very sub-optimal, but it is, after all, purely debug code.
2706 debug::DebugLock lock(producer->mutex);
2707 #endif
2708 struct Guard {
2709 Block *block;
2710 index_t index;
2711 BlockIndexEntry *entry;
2712 ConcurrentQueue *parent;
2713
2714 ~Guard() {
2715 (*block)[index]->~T();
2716 if (block->template set_empty<implicit_context>(index)) {
2717 entry->value.store(nullptr, std::memory_order_relaxed);
2718 parent->add_block_to_free_list(block);
2719 }
2720 }
2721 } guard = {block, index, entry, this->parent};
2722
2723 element = std::move(el);
2724 } else {
2725 element = std::move(el);
2726 el.~T();
2727
2728 if (block->template set_empty<implicit_context>(index)) {
2729 {
2730 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
2731 debug::DebugLock lock(mutex);
2732 #endif
2733 // Add the block back into the global free pool (and remove from block index)
2734 entry->value.store(nullptr, std::memory_order_relaxed);
2735 }
2736 this->parent->add_block_to_free_list(block); // releases the above store
2737 }
2738 }
2739
2740 return true;
2741 } else {
2742 this->dequeueOvercommit.fetch_add(1, std::memory_order_release);
2743 }
2744 }
2745
2746 return false;
2747 }
2748
2749 template <AllocationMode allocMode, typename It>
2750 bool enqueue_bulk(It itemFirst, size_t count) {
2751 // First, we need to make sure we have enough room to enqueue all of the elements;
2752 // this means pre-allocating blocks and putting them in the block index (but only if
2753 // all the allocations succeeded).
2754
2755 // Note that the tailBlock we start off with may not be owned by us any more;
2756 // this happens if it was filled up exactly to the top (setting tailIndex to
2757 // the first index of the next block which is not yet allocated), then dequeued
2758 // completely (putting it on the free list) before we enqueue again.
2759
2760 index_t startTailIndex = this->tailIndex.load(std::memory_order_relaxed);
2761 auto startBlock = this->tailBlock;
2762 Block *firstAllocatedBlock = nullptr;
2763 auto endBlock = this->tailBlock;
2764
2765 // Figure out how many blocks we'll need to allocate, and do so
2766 size_t blockBaseDiff = ((startTailIndex + count - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1))
2767 - ((startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1));
2768 index_t currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
2769 if (blockBaseDiff > 0) {
2770 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
2771 debug::DebugLock lock(mutex);
2772 #endif
2773 do {
2774 blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
2775 currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
2776
2777 // Find out where we'll be inserting this block in the block index
2778 BlockIndexEntry *idxEntry
2779 = nullptr; // initialization here unnecessary but compiler can't always tell
2780 Block *newBlock;
2781 bool indexInserted = false;
2782 auto head = this->headIndex.load(std::memory_order_relaxed);
2783 assert(!details::circular_less_than<index_t>(currentTailIndex, head));
2784 bool full = !details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE)
2785 || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value
2786 && (MAX_SUBQUEUE_SIZE == 0
2787 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head));
2788 if (full
2789 || !(indexInserted = insert_block_index_entry<allocMode>(idxEntry, currentTailIndex))
2790 || (newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>())
2791 == nullptr) {
2792 // Index allocation or block allocation failed; revert any other allocations
2793 // and index insertions done so far for this operation
2794 if (indexInserted) {
2795 rewind_block_index_tail();
2796 idxEntry->value.store(nullptr, std::memory_order_relaxed);
2797 }
2798 currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
2799 for (auto block = firstAllocatedBlock; block != nullptr; block = block->next) {
2800 currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
2801 idxEntry = get_block_index_entry_for_index(currentTailIndex);
2802 idxEntry->value.store(nullptr, std::memory_order_relaxed);
2803 rewind_block_index_tail();
2804 }
2805 this->parent->add_blocks_to_free_list(firstAllocatedBlock);
2806 this->tailBlock = startBlock;
2807
2808 return false;
2809 }
2810
2811 #if MCDBGQ_TRACKMEM
2812 newBlock->owner = this;
2813 #endif
2814 newBlock->template reset_empty<implicit_context>();
2815 newBlock->next = nullptr;
2816
2817 // Insert the new block into the index
2818 idxEntry->value.store(newBlock, std::memory_order_relaxed);
2819
2820 // Store the chain of blocks so that we can undo if later allocations fail,
2821 // and so that we can find the blocks when we do the actual enqueueing
2822 if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0
2823 || firstAllocatedBlock != nullptr) {
2824 assert(this->tailBlock != nullptr);
2825 this->tailBlock->next = newBlock;
2826 }
2827 this->tailBlock = newBlock;
2828 endBlock = newBlock;
2829 firstAllocatedBlock = firstAllocatedBlock == nullptr ? newBlock : firstAllocatedBlock;
2830 } while (blockBaseDiff > 0);
2831 }
2832
2833 // Enqueue, one block at a time
2834 index_t newTailIndex = startTailIndex + static_cast<index_t>(count);
2835 currentTailIndex = startTailIndex;
2836 this->tailBlock = startBlock;
2837 assert((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0
2838 || firstAllocatedBlock != nullptr || count == 0);
2839 if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0
2840 && firstAllocatedBlock != nullptr) {
2841 this->tailBlock = firstAllocatedBlock;
2842 }
2843 while (true) {
2844 auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1))
2845 + static_cast<index_t>(BLOCK_SIZE);
2846 if (details::circular_less_than<index_t>(newTailIndex, stopIndex)) {
2847 stopIndex = newTailIndex;
2848 }
2849 if (MOODYCAMEL_NOEXCEPT_CTOR(
2850 T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
2851 while (currentTailIndex != stopIndex) {
2852 new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++);
2853 }
2854 } else {
2855 MOODYCAMEL_TRY {
2856 while (currentTailIndex != stopIndex) {
2857 new ((*this->tailBlock)[currentTailIndex])
2858 T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst),
2859 new (nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst));
2860 ++currentTailIndex;
2861 ++itemFirst;
2862 }
2863 }
2864 MOODYCAMEL_CATCH(...) {
2865 auto constructedStopIndex = currentTailIndex;
2866 auto lastBlockEnqueued = this->tailBlock;
2867
2868 if (!details::is_trivially_destructible<T>::value) {
2869 auto block = startBlock;
2870 if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
2871 block = firstAllocatedBlock;
2872 }
2873 currentTailIndex = startTailIndex;
2874 while (true) {
2875 stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1))
2876 + static_cast<index_t>(BLOCK_SIZE);
2877 if (details::circular_less_than<index_t>(constructedStopIndex, stopIndex)) {
2878 stopIndex = constructedStopIndex;
2879 }
2880 while (currentTailIndex != stopIndex) {
2881 (*block)[currentTailIndex++]->~T();
2882 }
2883 if (block == lastBlockEnqueued) {
2884 break;
2885 }
2886 block = block->next;
2887 }
2888 }
2889
2890 currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
2891 for (auto block = firstAllocatedBlock; block != nullptr; block = block->next) {
2892 currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
2893 auto idxEntry = get_block_index_entry_for_index(currentTailIndex);
2894 idxEntry->value.store(nullptr, std::memory_order_relaxed);
2895 rewind_block_index_tail();
2896 }
2897 this->parent->add_blocks_to_free_list(firstAllocatedBlock);
2898 this->tailBlock = startBlock;
2899 MOODYCAMEL_RETHROW;
2900 }
2901 }
2902
2903 if (this->tailBlock == endBlock) {
2904 assert(currentTailIndex == newTailIndex);
2905 break;
2906 }
2907 this->tailBlock = this->tailBlock->next;
2908 }
2909 this->tailIndex.store(newTailIndex, std::memory_order_release);
2910 return true;
2911 }
2912
2913 template <typename It>
2914 size_t dequeue_bulk(It &itemFirst, size_t max) {
2915 auto tail = this->tailIndex.load(std::memory_order_relaxed);
2916 auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
2917 auto desiredCount = static_cast<size_t>(
2918 tail - (this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit));
2919 if (details::circular_less_than<size_t>(0, desiredCount)) {
2920 desiredCount = desiredCount < max ? desiredCount : max;
2921 std::atomic_thread_fence(std::memory_order_acquire);
2922
2923 auto myDequeueCount
2924 = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed);
2925 assert(overcommit <= myDequeueCount);
2926
2927 tail = this->tailIndex.load(std::memory_order_acquire);
2928 auto actualCount = static_cast<size_t>(tail - (myDequeueCount - overcommit));
2929 if (details::circular_less_than<size_t>(0, actualCount)) {
2930 actualCount = desiredCount < actualCount ? desiredCount : actualCount;
2931 if (actualCount < desiredCount) {
2932 this->dequeueOvercommit.fetch_add(
2933 desiredCount - actualCount, std::memory_order_release);
2934 }
2935
2936 // Get the first index. Note that since there's guaranteed to be at least actualCount
2937 // elements, this will never exceed tail.
2938 auto firstIndex = this->headIndex.fetch_add(actualCount, std::memory_order_acq_rel);
2939
2940 // Iterate the blocks and dequeue
2941 auto index = firstIndex;
2942 BlockIndexHeader *localBlockIndex;
2943 auto indexIndex = get_block_index_index_for_index(index, localBlockIndex);
2944 do {
2945 auto blockStartIndex = index;
2946 auto endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1))
2947 + static_cast<index_t>(BLOCK_SIZE);
2948 endIndex = details::circular_less_than<index_t>(
2949 firstIndex + static_cast<index_t>(actualCount), endIndex)
2950 ? firstIndex + static_cast<index_t>(actualCount)
2951 : endIndex;
2952
2953 auto entry = localBlockIndex->index[indexIndex];
2954 auto block = entry->value.load(std::memory_order_relaxed);
2955 if (MOODYCAMEL_NOEXCEPT_ASSIGN(
2956 T, T &&, details::deref_noexcept(itemFirst) = std::move((*(*block)[index])))) {
2957 while (index != endIndex) {
2958 auto &el = *((*block)[index]);
2959 *itemFirst++ = std::move(el);
2960 el.~T();
2961 ++index;
2962 }
2963 } else {
2964 MOODYCAMEL_TRY {
2965 while (index != endIndex) {
2966 auto &el = *((*block)[index]);
2967 *itemFirst = std::move(el);
2968 ++itemFirst;
2969 el.~T();
2970 ++index;
2971 }
2972 }
2973 MOODYCAMEL_CATCH(...) {
2974 do {
2975 entry = localBlockIndex->index[indexIndex];
2976 block = entry->value.load(std::memory_order_relaxed);
2977 while (index != endIndex) {
2978 (*block)[index++]->~T();
2979 }
2980
2981 if (block->template set_many_empty<implicit_context>(
2982 blockStartIndex, static_cast<size_t>(endIndex - blockStartIndex))) {
2983 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
2984 debug::DebugLock lock(mutex);
2985 #endif
2986 entry->value.store(nullptr, std::memory_order_relaxed);
2987 this->parent->add_block_to_free_list(block);
2988 }
2989 indexIndex = (indexIndex + 1) & (localBlockIndex->capacity - 1);
2990
2991 blockStartIndex = index;
2992 endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1))
2993 + static_cast<index_t>(BLOCK_SIZE);
2994 endIndex = details::circular_less_than<index_t>(
2995 firstIndex + static_cast<index_t>(actualCount), endIndex)
2996 ? firstIndex + static_cast<index_t>(actualCount)
2997 : endIndex;
2998 } while (index != firstIndex + actualCount);
2999
3000 MOODYCAMEL_RETHROW;
3001 }
3002 }
3003 if (block->template set_many_empty<implicit_context>(
3004 blockStartIndex, static_cast<size_t>(endIndex - blockStartIndex))) {
3005 {
3006 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
3007 debug::DebugLock lock(mutex);
3008 #endif
3009 // Note that the set_many_empty above did a release, meaning that anybody who
3010 // acquires the block we're about to free can use it safely since our writes (and
3011 // reads!) will have happened-before then.
3012 entry->value.store(nullptr, std::memory_order_relaxed);
3013 }
3014 this->parent->add_block_to_free_list(block); // releases the above store
3015 }
3016 indexIndex = (indexIndex + 1) & (localBlockIndex->capacity - 1);
3017 } while (index != firstIndex + actualCount);
3018
3019 return actualCount;
3020 } else {
3021 this->dequeueOvercommit.fetch_add(desiredCount, std::memory_order_release);
3022 }
3023 }
3024
3025 return 0;
3026 }
3027
3028 private:
3029 // The block size must be > 1, so any number with the low bit set is an invalid block base index
3030 static const index_t INVALID_BLOCK_BASE = 1;
3031
3032 struct BlockIndexEntry {
3033 std::atomic<index_t> key;
3034 std::atomic<Block *> value;
3035 };
3036
3037 struct BlockIndexHeader {
3038 size_t capacity;
3039 std::atomic<size_t> tail;
3040 BlockIndexEntry *entries;
3041 BlockIndexEntry **index;
3042 BlockIndexHeader *prev;
3043 };
3044
3045 template <AllocationMode allocMode>
3046 inline bool insert_block_index_entry(BlockIndexEntry *&idxEntry, index_t blockStartIndex) {
3047 auto localBlockIndex = blockIndex.load(
3048 std::memory_order_relaxed); // We're the only writer thread, relaxed is OK
3049 if (localBlockIndex == nullptr) {
3050 return false; // this can happen if new_block_index failed in the constructor
3051 }
3052 auto newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1)
3053 & (localBlockIndex->capacity - 1);
3054 idxEntry = localBlockIndex->index[newTail];
3055 if (idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE
3056 || idxEntry->value.load(std::memory_order_relaxed) == nullptr) {
3057 idxEntry->key.store(blockStartIndex, std::memory_order_relaxed);
3058 localBlockIndex->tail.store(newTail, std::memory_order_release);
3059 return true;
3060 }
3061
3062 // No room in the old block index, try to allocate another one!
3063 if (allocMode == CannotAlloc || !new_block_index()) {
3064 return false;
3065 }
3066 localBlockIndex = blockIndex.load(std::memory_order_relaxed);
3067 newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1)
3068 & (localBlockIndex->capacity - 1);
3069 idxEntry = localBlockIndex->index[newTail];
3070 assert(idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE);
3071 idxEntry->key.store(blockStartIndex, std::memory_order_relaxed);
3072 localBlockIndex->tail.store(newTail, std::memory_order_release);
3073 return true;
3074 }
3075
3076 inline void rewind_block_index_tail() {
3077 auto localBlockIndex = blockIndex.load(std::memory_order_relaxed);
3078 localBlockIndex->tail.store((localBlockIndex->tail.load(std::memory_order_relaxed) - 1)
3079 & (localBlockIndex->capacity - 1),
3080 std::memory_order_relaxed);
3081 }
3082
3083 inline BlockIndexEntry *get_block_index_entry_for_index(index_t index) const {
3084 BlockIndexHeader *localBlockIndex;
3085 auto idx = get_block_index_index_for_index(index, localBlockIndex);
3086 return localBlockIndex->index[idx];
3087 }
3088
3089 inline size_t get_block_index_index_for_index(
3090 index_t index, BlockIndexHeader *&localBlockIndex) const {
3091 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
3092 debug::DebugLock lock(mutex);
3093 #endif
3094 index &= ~static_cast<index_t>(BLOCK_SIZE - 1);
3095 localBlockIndex = blockIndex.load(std::memory_order_acquire);
3096 auto tail = localBlockIndex->tail.load(std::memory_order_acquire);
3097 auto tailBase = localBlockIndex->index[tail]->key.load(std::memory_order_relaxed);
3098 assert(tailBase != INVALID_BLOCK_BASE);
3099 // Note: Must use division instead of shift because the index may wrap around, causing a
3100 // negative offset, whose negativity we want to preserve
3101 auto offset = static_cast<size_t>(
3102 static_cast<typename std::make_signed<index_t>::type>(index - tailBase) / BLOCK_SIZE);
3103 size_t idx = (tail + offset) & (localBlockIndex->capacity - 1);
3104 assert(localBlockIndex->index[idx]->key.load(std::memory_order_relaxed) == index
3105 && localBlockIndex->index[idx]->value.load(std::memory_order_relaxed) != nullptr);
3106 return idx;
3107 }
3108
3109 bool new_block_index() {
3110 auto prev = blockIndex.load(std::memory_order_relaxed);
3111 size_t prevCapacity = prev == nullptr ? 0 : prev->capacity;
3112 auto entryCount = prev == nullptr ? nextBlockIndexCapacity : prevCapacity;
3113 auto raw = static_cast<char *>(
3114 (Traits::malloc)(sizeof(BlockIndexHeader) + std::alignment_of<BlockIndexEntry>::value - 1
3115 + sizeof(BlockIndexEntry) * entryCount
3116 + std::alignment_of<BlockIndexEntry *>::value - 1
3117 + sizeof(BlockIndexEntry *) * nextBlockIndexCapacity));
3118 if (raw == nullptr) {
3119 return false;
3120 }
3121
3122 auto header = new (raw) BlockIndexHeader;
3123 auto entries = reinterpret_cast<BlockIndexEntry *>(
3124 details::align_for<BlockIndexEntry>(raw + sizeof(BlockIndexHeader)));
3125 auto index = reinterpret_cast<BlockIndexEntry **>(details::align_for<BlockIndexEntry *>(
3126 reinterpret_cast<char *>(entries) + sizeof(BlockIndexEntry) * entryCount));
3127 if (prev != nullptr) {
3128 auto prevTail = prev->tail.load(std::memory_order_relaxed);
3129 auto prevPos = prevTail;
3130 size_t i = 0;
3131 do {
3132 prevPos = (prevPos + 1) & (prev->capacity - 1);
3133 index[i++] = prev->index[prevPos];
3134 } while (prevPos != prevTail);
3135 assert(i == prevCapacity);
3136 }
3137 for (size_t i = 0; i != entryCount; ++i) {
3138 new (entries + i) BlockIndexEntry;
3139 entries[i].key.store(INVALID_BLOCK_BASE, std::memory_order_relaxed);
3140 index[prevCapacity + i] = entries + i;
3141 }
3142 header->prev = prev;
3143 header->entries = entries;
3144 header->index = index;
3145 header->capacity = nextBlockIndexCapacity;
3146 header->tail.store(
3147 (prevCapacity - 1) & (nextBlockIndexCapacity - 1), std::memory_order_relaxed);
3148
3149 blockIndex.store(header, std::memory_order_release);
3150
3151 nextBlockIndexCapacity <<= 1;
3152
3153 return true;
3154 }
3155
3156 private:
3157 size_t nextBlockIndexCapacity;
3158 std::atomic<BlockIndexHeader *> blockIndex;
3159
3160 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
3161 public:
3162 details::ThreadExitListener threadExitListener;
3163
3164 private:
3165 #endif
3166
3167 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
3168 public:
3169 ImplicitProducer *nextImplicitProducer;
3170
3171 private:
3172 #endif
3173
3174 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
3175 mutable debug::DebugMutex mutex;
3176 #endif
3177 #if MCDBGQ_TRACKMEM
3178 friend struct MemStats;
3179 #endif
3180 };
3181
3182 //////////////////////////////////
3183 // Block pool manipulation
3184 //////////////////////////////////
3185
3186 void populate_initial_block_list(size_t blockCount) {
3187 initialBlockPoolSize = blockCount;
3188 if (initialBlockPoolSize == 0) {
3189 initialBlockPool = nullptr;
3190 return;
3191 }
3192
3193 initialBlockPool = create_array<Block>(blockCount);
3194 if (initialBlockPool == nullptr) {
3195 initialBlockPoolSize = 0;
3196 }
3197 for (size_t i = 0; i < initialBlockPoolSize; ++i) {
3198 initialBlockPool[i].dynamicallyAllocated = false;
3199 }
3200 }
3201
3202 inline Block *try_get_block_from_initial_pool() {
3203 if (initialBlockPoolIndex.load(std::memory_order_relaxed) >= initialBlockPoolSize) {
3204 return nullptr;
3205 }
3206
3207 auto index = initialBlockPoolIndex.fetch_add(1, std::memory_order_relaxed);
3208
3209 return index < initialBlockPoolSize ? (initialBlockPool + index) : nullptr;
3210 }
3211
3212 inline void add_block_to_free_list(Block *block) {
3213 #if MCDBGQ_TRACKMEM
3214 block->owner = nullptr;
3215 #endif
3216 freeList.add(block);
3217 }
3218
3219 inline void add_blocks_to_free_list(Block *block) {
3220 while (block != nullptr) {
3221 auto next = block->next;
3222 add_block_to_free_list(block);
3223 block = next;
3224 }
3225 }
3226
3227 inline Block *try_get_block_from_free_list() {
3228 return freeList.try_get();
3229 }
3230
3231 // Gets a free block from one of the memory pools, or allocates a new one (if applicable)
3232 template <AllocationMode canAlloc>
3233 Block *requisition_block() {
3234 auto block = try_get_block_from_initial_pool();
3235 if (block != nullptr) {
3236 return block;
3237 }
3238
3239 block = try_get_block_from_free_list();
3240 if (block != nullptr) {
3241 return block;
3242 }
3243
3244 if (canAlloc == CanAlloc) {
3245 return create<Block>();
3246 }
3247
3248 return nullptr;
3249 }
3250
3251 #if MCDBGQ_TRACKMEM
3252 public:
3253 struct MemStats {
3254 size_t allocatedBlocks;
3255 size_t usedBlocks;
3256 size_t freeBlocks;
3257 size_t ownedBlocksExplicit;
3258 size_t ownedBlocksImplicit;
3259 size_t implicitProducers;
3260 size_t explicitProducers;
3261 size_t elementsEnqueued;
3262 size_t blockClassBytes;
3263 size_t queueClassBytes;
3264 size_t implicitBlockIndexBytes;
3265 size_t explicitBlockIndexBytes;
3266
3267 friend class ConcurrentQueue;
3268
3269 private:
3270 static MemStats getFor(ConcurrentQueue *q) {
3271 MemStats stats = {0};
3272
3273 stats.elementsEnqueued = q->size_approx();
3274
3275 auto block = q->freeList.head_unsafe();
3276 while (block != nullptr) {
3277 ++stats.allocatedBlocks;
3278 ++stats.freeBlocks;
3279 block = block->freeListNext.load(std::memory_order_relaxed);
3280 }
3281
3282 for (auto ptr = q->producerListTail.load(std::memory_order_acquire); ptr != nullptr;
3283 ptr = ptr->next_prod()) {
3284 bool implicit = dynamic_cast<ImplicitProducer *>(ptr) != nullptr;
3285 stats.implicitProducers += implicit ? 1 : 0;
3286 stats.explicitProducers += implicit ? 0 : 1;
3287
3288 if (implicit) {
3289 auto prod = static_cast<ImplicitProducer *>(ptr);
3290 stats.queueClassBytes += sizeof(ImplicitProducer);
3291 auto head = prod->headIndex.load(std::memory_order_relaxed);
3292 auto tail = prod->tailIndex.load(std::memory_order_relaxed);
3293 auto hash = prod->blockIndex.load(std::memory_order_relaxed);
3294 if (hash != nullptr) {
3295 for (size_t i = 0; i != hash->capacity; ++i) {
3296 if (hash->index[i]->key.load(std::memory_order_relaxed)
3297 != ImplicitProducer::INVALID_BLOCK_BASE
3298 && hash->index[i]->value.load(std::memory_order_relaxed) != nullptr) {
3299 ++stats.allocatedBlocks;
3300 ++stats.ownedBlocksImplicit;
3301 }
3302 }
3303 stats.implicitBlockIndexBytes
3304 += hash->capacity * sizeof(typename ImplicitProducer::BlockIndexEntry);
3305 for (; hash != nullptr; hash = hash->prev) {
3306 stats.implicitBlockIndexBytes
3307 += sizeof(typename ImplicitProducer::BlockIndexHeader)
3308 + hash->capacity * sizeof(typename ImplicitProducer::BlockIndexEntry *);
3309 }
3310 }
3311 for (; details::circular_less_than<index_t>(head, tail); head += BLOCK_SIZE) {
3312 // auto block = prod->get_block_index_entry_for_index(head);
3313 ++stats.usedBlocks;
3314 }
3315 } else {
3316 auto prod = static_cast<ExplicitProducer *>(ptr);
3317 stats.queueClassBytes += sizeof(ExplicitProducer);
3318 auto tailBlock = prod->tailBlock;
3319 bool wasNonEmpty = false;
3320 if (tailBlock != nullptr) {
3321 auto block = tailBlock;
3322 do {
3323 ++stats.allocatedBlocks;
3324 if (!block->template is_empty<explicit_context>() || wasNonEmpty) {
3325 ++stats.usedBlocks;
3326 wasNonEmpty = wasNonEmpty || block != tailBlock;
3327 }
3328 ++stats.ownedBlocksExplicit;
3329 block = block->next;
3330 } while (block != tailBlock);
3331 }
3332 auto index = prod->blockIndex.load(std::memory_order_relaxed);
3333 while (index != nullptr) {
3334 stats.explicitBlockIndexBytes
3335 += sizeof(typename ExplicitProducer::BlockIndexHeader)
3336 + index->size * sizeof(typename ExplicitProducer::BlockIndexEntry);
3337 index = static_cast<typename ExplicitProducer::BlockIndexHeader *>(index->prev);
3338 }
3339 }
3340 }
3341
3342 auto freeOnInitialPool
3343 = q->initialBlockPoolIndex.load(std::memory_order_relaxed) >= q->initialBlockPoolSize
3344 ? 0
3345 : q->initialBlockPoolSize
3346 - q->initialBlockPoolIndex.load(std::memory_order_relaxed);
3347 stats.allocatedBlocks += freeOnInitialPool;
3348 stats.freeBlocks += freeOnInitialPool;
3349
3350 stats.blockClassBytes = sizeof(Block) * stats.allocatedBlocks;
3351 stats.queueClassBytes += sizeof(ConcurrentQueue);
3352
3353 return stats;
3354 }
3355 };
3356
3357 // For debugging only. Not thread-safe.
3358 MemStats getMemStats() {
3359 return MemStats::getFor(this);
3360 }
3361
3362 private:
3363 friend struct MemStats;
3364 #endif
3365
3366 //////////////////////////////////
3367 // Producer list manipulation
3368 //////////////////////////////////
3369
3370 ProducerBase *recycle_or_create_producer(bool isExplicit) {
3371 bool recycled;
3372 return recycle_or_create_producer(isExplicit, recycled);
3373 }
3374
3375 ProducerBase *recycle_or_create_producer(bool isExplicit, bool &recycled) {
3376 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
3377 debug::DebugLock lock(implicitProdMutex);
3378 #endif
3379 // Try to re-use one first
3380 for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr;
3381 ptr = ptr->next_prod()) {
3382 if (ptr->inactive.load(std::memory_order_relaxed) && ptr->isExplicit == isExplicit) {
3383 bool expected = true;
3384 if (ptr->inactive.compare_exchange_strong(expected, /* desired */ false,
3385 std::memory_order_acquire, std::memory_order_relaxed)) {
3386 // We caught one! It's been marked as activated, the caller can have it
3387 recycled = true;
3388 return ptr;
3389 }
3390 }
3391 }
3392
3393 recycled = false;
3394 return add_producer(isExplicit ? static_cast<ProducerBase *>(create<ExplicitProducer>(this))
3395 : create<ImplicitProducer>(this));
3396 }
3397
3398 ProducerBase *add_producer(ProducerBase *producer) {
3399 // Handle failed memory allocation
3400 if (producer == nullptr) {
3401 return nullptr;
3402 }
3403
3404 producerCount.fetch_add(1, std::memory_order_relaxed);
3405
3406 // Add it to the lock-free list
3407 auto prevTail = producerListTail.load(std::memory_order_relaxed);
3408 do {
3409 producer->next = prevTail;
3410 } while (!producerListTail.compare_exchange_weak(
3411 prevTail, producer, std::memory_order_release, std::memory_order_relaxed));
3412
3413 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
3414 if (producer->isExplicit) {
3415 auto prevTailExplicit = explicitProducers.load(std::memory_order_relaxed);
3416 do {
3417 static_cast<ExplicitProducer *>(producer)->nextExplicitProducer = prevTailExplicit;
3418 } while (!explicitProducers.compare_exchange_weak(prevTailExplicit,
3419 static_cast<ExplicitProducer *>(producer), std::memory_order_release,
3420 std::memory_order_relaxed));
3421 } else {
3422 auto prevTailImplicit = implicitProducers.load(std::memory_order_relaxed);
3423 do {
3424 static_cast<ImplicitProducer *>(producer)->nextImplicitProducer = prevTailImplicit;
3425 } while (!implicitProducers.compare_exchange_weak(prevTailImplicit,
3426 static_cast<ImplicitProducer *>(producer), std::memory_order_release,
3427 std::memory_order_relaxed));
3428 }
3429 #endif
3430
3431 return producer;
3432 }
3433
3434 void reown_producers() {
3435 // After another instance is moved-into/swapped-with this one, all the
3436 // producers we stole still think their parents are the other queue.
3437 // So fix them up!
3438 for (auto ptr = producerListTail.load(std::memory_order_relaxed); ptr != nullptr;
3439 ptr = ptr->next_prod()) {
3440 ptr->parent = this;
3441 }
3442 }
3443
3444 //////////////////////////////////
3445 // Implicit producer hash
3446 //////////////////////////////////
3447
3448 struct ImplicitProducerKVP {
3449 std::atomic<details::thread_id_t> key;
3450 ImplicitProducer *value; // No need for atomicity since it's only read by the thread that sets
3451 // it in the first place
3452
3453 ImplicitProducerKVP() : value(nullptr) {}
3454
3455 ImplicitProducerKVP(ImplicitProducerKVP &&other) MOODYCAMEL_NOEXCEPT {
3456 key.store(other.key.load(std::memory_order_relaxed), std::memory_order_relaxed);
3457 value = other.value;
3458 }
3459
3460 inline ImplicitProducerKVP &operator=(ImplicitProducerKVP &&other) MOODYCAMEL_NOEXCEPT {
3461 swap(other);
3462 return *this;
3463 }
3464
3465 inline void swap(ImplicitProducerKVP &other) MOODYCAMEL_NOEXCEPT {
3466 if (this != &other) {
3467 details::swap_relaxed(key, other.key);
3468 std::swap(value, other.value);
3469 }
3470 }
3471 };
3472
3473 template <typename XT, typename XTraits>
3474 friend void moodycamel::swap(typename ConcurrentQueue<XT, XTraits>::ImplicitProducerKVP &,
3475 typename ConcurrentQueue<XT, XTraits>::ImplicitProducerKVP &) MOODYCAMEL_NOEXCEPT;
3476
3477 struct ImplicitProducerHash {
3478 size_t capacity;
3479 ImplicitProducerKVP *entries;
3480 ImplicitProducerHash *prev;
3481 };
3482
3483 inline void populate_initial_implicit_producer_hash() {
3484 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
3485 return;
3486 }
3487
3488 implicitProducerHashCount.store(0, std::memory_order_relaxed);
3489 auto hash = &initialImplicitProducerHash;
3490 hash->capacity = INITIAL_IMPLICIT_PRODUCER_HASH_SIZE;
3491 hash->entries = &initialImplicitProducerHashEntries[0];
3492 for (size_t i = 0; i != INITIAL_IMPLICIT_PRODUCER_HASH_SIZE; ++i) {
3493 initialImplicitProducerHashEntries[i].key.store(
3494 details::invalid_thread_id, std::memory_order_relaxed);
3495 }
3496 hash->prev = nullptr;
3497 implicitProducerHash.store(hash, std::memory_order_relaxed);
3498 }
3499
3500 void swap_implicit_producer_hashes(ConcurrentQueue &other) {
3501 if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) {
3502 return;
3503 }
3504
3505 // Swap (assumes our implicit producer hash is initialized)
3506 initialImplicitProducerHashEntries.swap(other.initialImplicitProducerHashEntries);
3507 initialImplicitProducerHash.entries = &initialImplicitProducerHashEntries[0];
3508 other.initialImplicitProducerHash.entries = &other.initialImplicitProducerHashEntries[0];
3509
3510 details::swap_relaxed(implicitProducerHashCount, other.implicitProducerHashCount);
3511
3512 details::swap_relaxed(implicitProducerHash, other.implicitProducerHash);
3513 if (implicitProducerHash.load(std::memory_order_relaxed)
3514 == &other.initialImplicitProducerHash) {
3515 implicitProducerHash.store(&initialImplicitProducerHash, std::memory_order_relaxed);
3516 } else {
3517 ImplicitProducerHash *hash;
3518 for (hash = implicitProducerHash.load(std::memory_order_relaxed);
3519 hash->prev != &other.initialImplicitProducerHash; hash = hash->prev) {
3520 continue;
3521 }
3522 hash->prev = &initialImplicitProducerHash;
3523 }
3524 if (other.implicitProducerHash.load(std::memory_order_relaxed)
3525 == &initialImplicitProducerHash) {
3526 other.implicitProducerHash.store(
3527 &other.initialImplicitProducerHash, std::memory_order_relaxed);
3528 } else {
3529 ImplicitProducerHash *hash;
3530 for (hash = other.implicitProducerHash.load(std::memory_order_relaxed);
3531 hash->prev != &initialImplicitProducerHash; hash = hash->prev) {
3532 continue;
3533 }
3534 hash->prev = &other.initialImplicitProducerHash;
3535 }
3536 }
3537
3538 // Only fails (returns nullptr) if memory allocation fails
3539 ImplicitProducer *get_or_add_implicit_producer() {
3540 // Note that since the data is essentially thread-local (key is thread ID),
3541 // there's a reduced need for fences (memory ordering is already consistent
3542 // for any individual thread), except for the current table itself.
3543
3544 // Start by looking for the thread ID in the current and all previous hash tables.
3545 // If it's not found, it must not be in there yet, since this same thread would
3546 // have added it previously to one of the tables that we traversed.
3547
3548 // Code and algorithm adapted from
3549 // http://preshing.com/20130605/the-worlds-simplest-lock-free-hash-table
3550
3551 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
3552 debug::DebugLock lock(implicitProdMutex);
3553 #endif
3554
3555 auto id = details::thread_id();
3556 auto hashedId = details::hash_thread_id(id);
3557
3558 auto mainHash = implicitProducerHash.load(std::memory_order_acquire);
3559 for (auto hash = mainHash; hash != nullptr; hash = hash->prev) {
3560 // Look for the id in this hash
3561 auto index = hashedId;
3562 while (true) { // Not an infinite loop because at least one slot is free in the hash table
3563 index &= hash->capacity - 1;
3564
3565 auto probedKey = hash->entries[index].key.load(std::memory_order_relaxed);
3566 if (probedKey == id) {
3567 // Found it! If we had to search several hashes deep, though, we should lazily add it
3568 // to the current main hash table to avoid the extended search next time.
3569 // Note there's guaranteed to be room in the current hash table since every subsequent
3570 // table implicitly reserves space for all previous tables (there's only one
3571 // implicitProducerHashCount).
3572 auto value = hash->entries[index].value;
3573 if (hash != mainHash) {
3574 index = hashedId;
3575 while (true) {
3576 index &= mainHash->capacity - 1;
3577 probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed);
3578 auto empty = details::invalid_thread_id;
3579 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
3580 auto reusable = details::invalid_thread_id2;
3581 if ((probedKey == empty
3582 && mainHash->entries[index].key.compare_exchange_strong(
3583 empty, id, std::memory_order_relaxed, std::memory_order_relaxed))
3584 || (probedKey == reusable
3585 && mainHash->entries[index].key.compare_exchange_strong(
3586 reusable, id, std::memory_order_acquire, std::memory_order_acquire))) {
3587 #else
3588 if ((probedKey == empty
3589 && mainHash->entries[index].key.compare_exchange_strong(
3590 empty, id, std::memory_order_relaxed, std::memory_order_relaxed))) {
3591 #endif
3592 mainHash->entries[index].value = value;
3593 break;
3594 }
3595 ++index;
3596 }
3597 }
3598
3599 return value;
3600 }
3601 if (probedKey == details::invalid_thread_id) {
3602 break; // Not in this hash table
3603 }
3604 ++index;
3605 }
3606 }
3607
3608 // Insert!
3609 auto newCount = 1 + implicitProducerHashCount.fetch_add(1, std::memory_order_relaxed);
3610 while (true) {
3611 if (newCount >= (mainHash->capacity >> 1)
3612 && !implicitProducerHashResizeInProgress.test_and_set(std::memory_order_acquire)) {
3613 // We've acquired the resize lock, try to allocate a bigger hash table.
3614 // Note the acquire fence synchronizes with the release fence at the end of this block, and
3615 // hence when we reload implicitProducerHash it must be the most recent version (it only
3616 // gets changed within this locked block).
3617 mainHash = implicitProducerHash.load(std::memory_order_acquire);
3618 if (newCount >= (mainHash->capacity >> 1)) {
3619 auto newCapacity = mainHash->capacity << 1;
3620 while (newCount >= (newCapacity >> 1)) {
3621 newCapacity <<= 1;
3622 }
3623 auto raw = static_cast<char *>(
3624 (Traits::malloc)(sizeof(ImplicitProducerHash)
3625 + std::alignment_of<ImplicitProducerKVP>::value - 1
3626 + sizeof(ImplicitProducerKVP) * newCapacity));
3627 if (raw == nullptr) {
3628 // Allocation failed
3629 implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed);
3630 implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
3631 return nullptr;
3632 }
3633
3634 auto newHash = new (raw) ImplicitProducerHash;
3635 newHash->capacity = newCapacity;
3636 newHash->entries = reinterpret_cast<ImplicitProducerKVP *>(
3637 details::align_for<ImplicitProducerKVP>(raw + sizeof(ImplicitProducerHash)));
3638 for (size_t i = 0; i != newCapacity; ++i) {
3639 new (newHash->entries + i) ImplicitProducerKVP;
3640 newHash->entries[i].key.store(details::invalid_thread_id, std::memory_order_relaxed);
3641 }
3642 newHash->prev = mainHash;
3643 implicitProducerHash.store(newHash, std::memory_order_release);
3644 implicitProducerHashResizeInProgress.clear(std::memory_order_release);
3645 mainHash = newHash;
3646 } else {
3647 implicitProducerHashResizeInProgress.clear(std::memory_order_release);
3648 }
3649 }
3650
3651 // If it's < three-quarters full, add to the old one anyway so that we don't have to wait for
3652 // the next table to finish being allocated by another thread (and if we just finished
3653 // allocating above, the condition will always be true)
3654 if (newCount < (mainHash->capacity >> 1) + (mainHash->capacity >> 2)) {
3655 bool recycled;
3656 auto producer
3657 = static_cast<ImplicitProducer *>(recycle_or_create_producer(false, recycled));
3658 if (producer == nullptr) {
3659 implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed);
3660 return nullptr;
3661 }
3662 if (recycled) {
3663 implicitProducerHashCount.fetch_sub(1, std::memory_order_relaxed);
3664 }
3665
3666 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
3667 producer->threadExitListener.callback
3668 = &ConcurrentQueue::implicit_producer_thread_exited_callback;
3669 producer->threadExitListener.userData = producer;
3670 details::ThreadExitNotifier::subscribe(&producer->threadExitListener);
3671 #endif
3672
3673 auto index = hashedId;
3674 while (true) {
3675 index &= mainHash->capacity - 1;
3676 auto probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed);
3677
3678 auto empty = details::invalid_thread_id;
3679 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
3680 auto reusable = details::invalid_thread_id2;
3681 if ((probedKey == empty
3682 && mainHash->entries[index].key.compare_exchange_strong(
3683 empty, id, std::memory_order_relaxed, std::memory_order_relaxed))
3684 || (probedKey == reusable
3685 && mainHash->entries[index].key.compare_exchange_strong(
3686 reusable, id, std::memory_order_acquire, std::memory_order_acquire))) {
3687 #else
3688 if ((probedKey == empty
3689 && mainHash->entries[index].key.compare_exchange_strong(
3690 empty, id, std::memory_order_relaxed, std::memory_order_relaxed))) {
3691 #endif
3692 mainHash->entries[index].value = producer;
3693 break;
3694 }
3695 ++index;
3696 }
3697 return producer;
3698 }
3699
3700 // Hmm, the old hash is quite full and somebody else is busy allocating a new one.
3701 // We need to wait for the allocating thread to finish (if it succeeds, we add, if not,
3702 // we try to allocate ourselves).
3703 mainHash = implicitProducerHash.load(std::memory_order_acquire);
3704 }
3705 }
3706
3707 #ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
3708 void implicit_producer_thread_exited(ImplicitProducer *producer) {
3709 // Remove from thread exit listeners
3710 details::ThreadExitNotifier::unsubscribe(&producer->threadExitListener);
3711
3712 // Remove from hash
3713 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
3714 debug::DebugLock lock(implicitProdMutex);
3715 #endif
3716 auto hash = implicitProducerHash.load(std::memory_order_acquire);
3717 assert(hash != nullptr); // The thread exit listener is only registered if we were added to a
3718 // hash in the first place
3719 auto id = details::thread_id();
3720 auto hashedId = details::hash_thread_id(id);
3721 details::thread_id_t probedKey;
3722
3723 // We need to traverse all the hashes just in case other threads aren't on the current one yet
3724 // and are trying to add an entry thinking there's a free slot (because they reused a producer)
3725 for (; hash != nullptr; hash = hash->prev) {
3726 auto index = hashedId;
3727 do {
3728 index &= hash->capacity - 1;
3729 probedKey = hash->entries[index].key.load(std::memory_order_relaxed);
3730 if (probedKey == id) {
3731 hash->entries[index].key.store(details::invalid_thread_id2, std::memory_order_release);
3732 break;
3733 }
3734 ++index;
3735 } while (
3736 probedKey != details::invalid_thread_id); // Can happen if the hash has changed but we
3737 // weren't put back in it yet, or if we weren't
3738 // added to this hash in the first place
3739 }
3740
3741 // Mark the queue as being recyclable
3742 producer->inactive.store(true, std::memory_order_release);
3743 }
3744
3745 static void implicit_producer_thread_exited_callback(void *userData) {
3746 auto producer = static_cast<ImplicitProducer *>(userData);
3747 auto queue = producer->parent;
3748 queue->implicit_producer_thread_exited(producer);
3749 }
3750 #endif
3751
3752 //////////////////////////////////
3753 // Utility functions
3754 //////////////////////////////////
3755
3756 template <typename U>
3757 static inline U *create_array(size_t count) {
3758 assert(count > 0);
3759 auto p = static_cast<U *>((Traits::malloc)(sizeof(U) * count));
3760 if (p == nullptr) {
3761 return nullptr;
3762 }
3763
3764 for (size_t i = 0; i != count; ++i) {
3765 new (p + i) U();
3766 }
3767 return p;
3768 }
3769
3770 template <typename U>
3771 static inline void destroy_array(U *p, size_t count) {
3772 if (p != nullptr) {
3773 assert(count > 0);
3774 for (size_t i = count; i != 0;) {
3775 (p + --i)->~U();
3776 }
3777 (Traits::free)(p);
3778 }
3779 }
3780
3781 template <typename U>
3782 static inline U *create() {
3783 auto p = (Traits::malloc)(sizeof(U));
3784 return p != nullptr ? new (p) U : nullptr;
3785 }
3786
3787 template <typename U, typename A1>
3788 static inline U *create(A1 &&a1) {
3789 auto p = (Traits::malloc)(sizeof(U));
3790 return p != nullptr ? new (p) U(std::forward<A1>(a1)) : nullptr;
3791 }
3792
3793 template <typename U>
3794 static inline void destroy(U *p) {
3795 if (p != nullptr) {
3796 p->~U();
3797 }
3798 (Traits::free)(p);
3799 }
3800
3801 private:
3802 std::atomic<ProducerBase *> producerListTail;
3803 std::atomic<std::uint32_t> producerCount;
3804
3805 std::atomic<size_t> initialBlockPoolIndex;
3806 Block *initialBlockPool;
3807 size_t initialBlockPoolSize;
3808
3809 #if !MCDBGQ_USEDEBUGFREELIST
3810 FreeList<Block> freeList;
3811 #else
3812 debug::DebugFreeList<Block> freeList;
3813 #endif
3814
3815 std::atomic<ImplicitProducerHash *> implicitProducerHash;
3816 std::atomic<size_t> implicitProducerHashCount; // Number of slots logically used
3817 ImplicitProducerHash initialImplicitProducerHash;
3818 std::array<ImplicitProducerKVP, INITIAL_IMPLICIT_PRODUCER_HASH_SIZE>
3819 initialImplicitProducerHashEntries;
3820 std::atomic_flag implicitProducerHashResizeInProgress;
3821
3822 std::atomic<std::uint32_t> nextExplicitConsumerId;
3823 std::atomic<std::uint32_t> globalExplicitConsumerOffset;
3824
3825 #if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
3826 debug::DebugMutex implicitProdMutex;
3827 #endif
3828
3829 #ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
3830 std::atomic<ExplicitProducer *> explicitProducers;
3831 std::atomic<ImplicitProducer *> implicitProducers;
3832 #endif
3833 };
3834
3835 template <typename T, typename Traits>
3836 ProducerToken::ProducerToken(ConcurrentQueue<T, Traits> &queue)
3837 : producer(queue.recycle_or_create_producer(true)) {
3838 if (producer != nullptr) {
3839 producer->token = this;
3840 }
3841 }
3842
3843 template <typename T, typename Traits>
3844 ProducerToken::ProducerToken(BlockingConcurrentQueue<T, Traits> &queue)
3845 : producer(reinterpret_cast<ConcurrentQueue<T, Traits> *>(&queue)->recycle_or_create_producer(
3846 true)) {
3847 if (producer != nullptr) {
3848 producer->token = this;
3849 }
3850 }
3851
3852 template <typename T, typename Traits>
3853 ConsumerToken::ConsumerToken(ConcurrentQueue<T, Traits> &queue)
3854 : itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr) {
3855 initialOffset = queue.nextExplicitConsumerId.fetch_add(1, std::memory_order_release);
3856 lastKnownGlobalOffset = -1;
3857 }
3858
3859 template <typename T, typename Traits>
3860 ConsumerToken::ConsumerToken(BlockingConcurrentQueue<T, Traits> &queue)
3861 : itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr) {
3862 initialOffset
3863 = reinterpret_cast<ConcurrentQueue<T, Traits> *>(&queue)->nextExplicitConsumerId.fetch_add(
3864 1, std::memory_order_release);
3865 lastKnownGlobalOffset = -1;
3866 }
3867
3868 template <typename T, typename Traits>
3869 inline void swap(ConcurrentQueue<T, Traits> &a, ConcurrentQueue<T, Traits> &b) MOODYCAMEL_NOEXCEPT {
3870 a.swap(b);
3871 }
3872
3873 inline void swap(ProducerToken &a, ProducerToken &b) MOODYCAMEL_NOEXCEPT {
3874 a.swap(b);
3875 }
3876
3877 inline void swap(ConsumerToken &a, ConsumerToken &b) MOODYCAMEL_NOEXCEPT {
3878 a.swap(b);
3879 }
3880
3881 template <typename T, typename Traits>
3882 inline void swap(typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP &a,
3883 typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP &b) MOODYCAMEL_NOEXCEPT {
3884 a.swap(b);
3885 }
3886
3887 } // namespace moodycamel
3888
3889 } // namespace dmlc
3890
3891 #if defined(__GNUC__)
3892
3893 #endif
3894
3895 #endif // DMLC_CONCURRENTQUEUE_H_
3896 //! \endcond Doxygen_Suppress