Debian Codegraph @

thirdparty/concurrentqueue.h

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