netgen-mesher 6.2.2506.post35.dev0__cp314-cp314-win_amd64.whl

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