You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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