Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

3638 řádky
143 KiB

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