erlang各种有用的函数包括一些有用nif封装,还有一些性能测试case。
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

3744 satır
148 KiB

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