barrier 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP_BARRIER
  10. #define _LIBCPP_BARRIER
  11. /*
  12. barrier synopsis
  13. namespace std
  14. {
  15. template<class CompletionFunction = see below>
  16. class barrier
  17. {
  18. public:
  19. using arrival_token = see below;
  20. static constexpr ptrdiff_t max() noexcept;
  21. constexpr explicit barrier(ptrdiff_t phase_count,
  22. CompletionFunction f = CompletionFunction());
  23. ~barrier();
  24. barrier(const barrier&) = delete;
  25. barrier& operator=(const barrier&) = delete;
  26. [[nodiscard]] arrival_token arrive(ptrdiff_t update = 1);
  27. void wait(arrival_token&& arrival) const;
  28. void arrive_and_wait();
  29. void arrive_and_drop();
  30. private:
  31. CompletionFunction completion; // exposition only
  32. };
  33. }
  34. */
  35. #include <__assert> // all public C++ headers provide the assertion handler
  36. #include <__atomic/atomic_base.h>
  37. #include <__atomic/memory_order.h>
  38. #include <__availability>
  39. #include <__config>
  40. #include <__memory/unique_ptr.h>
  41. #include <__thread/poll_with_backoff.h>
  42. #include <__thread/timed_backoff_policy.h>
  43. #include <__utility/move.h>
  44. #include <cstddef>
  45. #include <cstdint>
  46. #include <limits>
  47. #include <version>
  48. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  49. # pragma GCC system_header
  50. #endif
  51. #ifdef _LIBCPP_HAS_NO_THREADS
  52. # error "<barrier> is not supported since libc++ has been configured without support for threads."
  53. #endif
  54. _LIBCPP_PUSH_MACROS
  55. #include <__undef_macros>
  56. #if _LIBCPP_STD_VER >= 14
  57. _LIBCPP_BEGIN_NAMESPACE_STD
  58. struct __empty_completion
  59. {
  60. inline _LIBCPP_INLINE_VISIBILITY
  61. void operator()() noexcept
  62. {
  63. }
  64. };
  65. #ifndef _LIBCPP_HAS_NO_TREE_BARRIER
  66. /*
  67. The default implementation of __barrier_base is a classic tree barrier.
  68. It looks different from literature pseudocode for two main reasons:
  69. 1. Threads that call into std::barrier functions do not provide indices,
  70. so a numbering step is added before the actual barrier algorithm,
  71. appearing as an N+1 round to the N rounds of the tree barrier.
  72. 2. A great deal of attention has been paid to avoid cache line thrashing
  73. by flattening the tree structure into cache-line sized arrays, that
  74. are indexed in an efficient way.
  75. */
  76. using __barrier_phase_t = uint8_t;
  77. class __barrier_algorithm_base;
  78. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI
  79. __barrier_algorithm_base* __construct_barrier_algorithm_base(ptrdiff_t& __expected);
  80. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI
  81. bool __arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier,
  82. __barrier_phase_t __old_phase);
  83. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI
  84. void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier);
  85. template<class _CompletionF>
  86. class __barrier_base {
  87. ptrdiff_t __expected_;
  88. unique_ptr<__barrier_algorithm_base,
  89. void (*)(__barrier_algorithm_base*)> __base_;
  90. __atomic_base<ptrdiff_t> __expected_adjustment_;
  91. _CompletionF __completion_;
  92. __atomic_base<__barrier_phase_t> __phase_;
  93. public:
  94. using arrival_token = __barrier_phase_t;
  95. static _LIBCPP_HIDE_FROM_ABI constexpr ptrdiff_t max() noexcept {
  96. return numeric_limits<ptrdiff_t>::max();
  97. }
  98. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  99. __barrier_base(ptrdiff_t __expected, _CompletionF __completion = _CompletionF())
  100. : __expected_(__expected), __base_(std::__construct_barrier_algorithm_base(this->__expected_),
  101. &__destroy_barrier_algorithm_base),
  102. __expected_adjustment_(0), __completion_(std::move(__completion)), __phase_(0)
  103. {
  104. }
  105. [[__nodiscard__]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  106. arrival_token arrive(ptrdiff_t __update)
  107. {
  108. _LIBCPP_ASSERT_UNCATEGORIZED(
  109. __update <= __expected_, "update is greater than the expected count for the current barrier phase");
  110. auto const __old_phase = __phase_.load(memory_order_relaxed);
  111. for(; __update; --__update)
  112. if(__arrive_barrier_algorithm_base(__base_.get(), __old_phase)) {
  113. __completion_();
  114. __expected_ += __expected_adjustment_.load(memory_order_relaxed);
  115. __expected_adjustment_.store(0, memory_order_relaxed);
  116. __phase_.store(__old_phase + 2, memory_order_release);
  117. __phase_.notify_all();
  118. }
  119. return __old_phase;
  120. }
  121. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  122. void wait(arrival_token&& __old_phase) const
  123. {
  124. auto const __test_fn = [this, __old_phase]() -> bool {
  125. return __phase_.load(memory_order_acquire) != __old_phase;
  126. };
  127. std::__libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy());
  128. }
  129. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  130. void arrive_and_drop()
  131. {
  132. __expected_adjustment_.fetch_sub(1, memory_order_relaxed);
  133. (void)arrive(1);
  134. }
  135. };
  136. #else
  137. /*
  138. The alternative implementation of __barrier_base is a central barrier.
  139. Two versions of this algorithm are provided:
  140. 1. A fairly straightforward implementation of the litterature for the
  141. general case where the completion function is not empty.
  142. 2. An optimized implementation that exploits 2's complement arithmetic
  143. and well-defined overflow in atomic arithmetic, to handle the phase
  144. roll-over for free.
  145. */
  146. template<class _CompletionF>
  147. class __barrier_base {
  148. __atomic_base<ptrdiff_t> __expected;
  149. __atomic_base<ptrdiff_t> __arrived;
  150. _CompletionF __completion;
  151. __atomic_base<bool> __phase;
  152. public:
  153. using arrival_token = bool;
  154. static constexpr ptrdiff_t max() noexcept {
  155. return numeric_limits<ptrdiff_t>::max();
  156. }
  157. _LIBCPP_INLINE_VISIBILITY
  158. __barrier_base(ptrdiff_t __expected, _CompletionF __completion = _CompletionF())
  159. : __expected(__expected), __arrived(__expected), __completion(std::move(__completion)), __phase(false)
  160. {
  161. }
  162. [[nodiscard]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  163. arrival_token arrive(ptrdiff_t update)
  164. {
  165. auto const __old_phase = __phase.load(memory_order_relaxed);
  166. auto const __result = __arrived.fetch_sub(update, memory_order_acq_rel) - update;
  167. auto const new_expected = __expected.load(memory_order_relaxed);
  168. _LIBCPP_ASSERT_UNCATEGORIZED(
  169. update <= new_expected, "update is greater than the expected count for the current barrier phase");
  170. if (0 == __result) {
  171. __completion();
  172. __arrived.store(new_expected, memory_order_relaxed);
  173. __phase.store(!__old_phase, memory_order_release);
  174. __phase.notify_all();
  175. }
  176. return __old_phase;
  177. }
  178. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  179. void wait(arrival_token&& __old_phase) const
  180. {
  181. __phase.wait(__old_phase, memory_order_acquire);
  182. }
  183. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  184. void arrive_and_drop()
  185. {
  186. __expected.fetch_sub(1, memory_order_relaxed);
  187. (void)arrive(1);
  188. }
  189. };
  190. template<>
  191. class __barrier_base<__empty_completion> {
  192. static constexpr uint64_t __expected_unit = 1ull;
  193. static constexpr uint64_t __arrived_unit = 1ull << 32;
  194. static constexpr uint64_t __expected_mask = __arrived_unit - 1;
  195. static constexpr uint64_t __phase_bit = 1ull << 63;
  196. static constexpr uint64_t __arrived_mask = (__phase_bit - 1) & ~__expected_mask;
  197. __atomic_base<uint64_t> __phase_arrived_expected;
  198. static _LIBCPP_INLINE_VISIBILITY
  199. constexpr uint64_t __init(ptrdiff_t __count) _NOEXCEPT
  200. {
  201. return ((uint64_t(1u << 31) - __count) << 32)
  202. | (uint64_t(1u << 31) - __count);
  203. }
  204. public:
  205. using arrival_token = uint64_t;
  206. static constexpr ptrdiff_t max() noexcept {
  207. return ptrdiff_t(1u << 31) - 1;
  208. }
  209. _LIBCPP_INLINE_VISIBILITY
  210. explicit inline __barrier_base(ptrdiff_t __count, __empty_completion = __empty_completion())
  211. : __phase_arrived_expected(__init(__count))
  212. {
  213. }
  214. [[nodiscard]] inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  215. arrival_token arrive(ptrdiff_t update)
  216. {
  217. auto const __inc = __arrived_unit * update;
  218. auto const __old = __phase_arrived_expected.fetch_add(__inc, memory_order_acq_rel);
  219. _LIBCPP_ASSERT_UNCATEGORIZED(
  220. update <= __old, "update is greater than the expected count for the current barrier phase");
  221. if ((__old ^ (__old + __inc)) & __phase_bit) {
  222. __phase_arrived_expected.fetch_add((__old & __expected_mask) << 32, memory_order_relaxed);
  223. __phase_arrived_expected.notify_all();
  224. }
  225. return __old & __phase_bit;
  226. }
  227. inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  228. void wait(arrival_token&& __phase) const
  229. {
  230. auto const __test_fn = [=]() -> bool {
  231. uint64_t const __current = __phase_arrived_expected.load(memory_order_acquire);
  232. return ((__current & __phase_bit) != __phase);
  233. };
  234. __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy());
  235. }
  236. inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  237. void arrive_and_drop()
  238. {
  239. __phase_arrived_expected.fetch_add(__expected_unit, memory_order_relaxed);
  240. (void)arrive(1);
  241. }
  242. };
  243. #endif // !_LIBCPP_HAS_NO_TREE_BARRIER
  244. template<class _CompletionF = __empty_completion>
  245. class barrier {
  246. __barrier_base<_CompletionF> __b_;
  247. public:
  248. using arrival_token = typename __barrier_base<_CompletionF>::arrival_token;
  249. static _LIBCPP_HIDE_FROM_ABI constexpr ptrdiff_t max() noexcept {
  250. return __barrier_base<_CompletionF>::max();
  251. }
  252. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  253. explicit barrier(ptrdiff_t __count, _CompletionF __completion = _CompletionF())
  254. : __b_(__count, _VSTD::move(__completion)) {
  255. _LIBCPP_ASSERT_UNCATEGORIZED(
  256. __count >= 0,
  257. "barrier::barrier(ptrdiff_t, CompletionFunction): barrier cannot be initialized with a negative value");
  258. _LIBCPP_ASSERT_UNCATEGORIZED(
  259. __count <= max(),
  260. "barrier::barrier(ptrdiff_t, CompletionFunction): barrier cannot be initialized with "
  261. "a value greater than max()");
  262. }
  263. barrier(barrier const&) = delete;
  264. barrier& operator=(barrier const&) = delete;
  265. [[__nodiscard__]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  266. arrival_token arrive(ptrdiff_t __update = 1)
  267. {
  268. _LIBCPP_ASSERT_UNCATEGORIZED(__update > 0, "barrier:arrive must be called with a value greater than 0");
  269. return __b_.arrive(__update);
  270. }
  271. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  272. void wait(arrival_token&& __phase) const
  273. {
  274. __b_.wait(_VSTD::move(__phase));
  275. }
  276. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  277. void arrive_and_wait()
  278. {
  279. wait(arrive());
  280. }
  281. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  282. void arrive_and_drop()
  283. {
  284. __b_.arrive_and_drop();
  285. }
  286. };
  287. _LIBCPP_END_NAMESPACE_STD
  288. #endif // _LIBCPP_STD_VER >= 14
  289. _LIBCPP_POP_MACROS
  290. #if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
  291. # include <atomic>
  292. # include <concepts>
  293. # include <iterator>
  294. # include <memory>
  295. # include <stdexcept>
  296. # include <variant>
  297. #endif
  298. #endif //_LIBCPP_BARRIER