barrier 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 <__config>
  36. #ifdef _LIBCPP_HAS_NO_THREADS
  37. # error "<barrier> is not supported since libc++ has been configured without support for threads."
  38. #endif
  39. #include <__assert>
  40. #include <__atomic/atomic_base.h>
  41. #include <__atomic/memory_order.h>
  42. #include <__availability>
  43. #include <__memory/unique_ptr.h>
  44. #include <__thread/poll_with_backoff.h>
  45. #include <__thread/timed_backoff_policy.h>
  46. #include <__utility/move.h>
  47. #include <cstddef>
  48. #include <cstdint>
  49. #include <limits>
  50. #include <version>
  51. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  52. # pragma GCC system_header
  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. inline _LIBCPP_HIDE_FROM_ABI void operator()() noexcept {}
  60. };
  61. # ifndef _LIBCPP_HAS_NO_TREE_BARRIER
  62. /*
  63. The default implementation of __barrier_base is a classic tree barrier.
  64. It looks different from literature pseudocode for two main reasons:
  65. 1. Threads that call into std::barrier functions do not provide indices,
  66. so a numbering step is added before the actual barrier algorithm,
  67. appearing as an N+1 round to the N rounds of the tree barrier.
  68. 2. A great deal of attention has been paid to avoid cache line thrashing
  69. by flattening the tree structure into cache-line sized arrays, that
  70. are indexed in an efficient way.
  71. */
  72. using __barrier_phase_t = uint8_t;
  73. class __barrier_algorithm_base;
  74. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI __barrier_algorithm_base*
  75. __construct_barrier_algorithm_base(ptrdiff_t& __expected);
  76. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI bool
  77. __arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier, __barrier_phase_t __old_phase);
  78. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_EXPORTED_FROM_ABI void
  79. __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier);
  80. template <class _CompletionF>
  81. class __barrier_base {
  82. ptrdiff_t __expected_;
  83. unique_ptr<__barrier_algorithm_base, void (*)(__barrier_algorithm_base*)> __base_;
  84. __atomic_base<ptrdiff_t> __expected_adjustment_;
  85. _CompletionF __completion_;
  86. __atomic_base<__barrier_phase_t> __phase_;
  87. public:
  88. using arrival_token = __barrier_phase_t;
  89. static _LIBCPP_HIDE_FROM_ABI constexpr ptrdiff_t max() noexcept { return numeric_limits<ptrdiff_t>::max(); }
  90. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI
  91. __barrier_base(ptrdiff_t __expected, _CompletionF __completion = _CompletionF())
  92. : __expected_(__expected),
  93. __base_(std::__construct_barrier_algorithm_base(this->__expected_), &__destroy_barrier_algorithm_base),
  94. __expected_adjustment_(0),
  95. __completion_(std::move(__completion)),
  96. __phase_(0) {}
  97. [[__nodiscard__]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI arrival_token arrive(ptrdiff_t __update) {
  98. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
  99. __update <= __expected_, "update is greater than the expected count for the current barrier phase");
  100. auto const __old_phase = __phase_.load(memory_order_relaxed);
  101. for (; __update; --__update)
  102. if (__arrive_barrier_algorithm_base(__base_.get(), __old_phase)) {
  103. __completion_();
  104. __expected_ += __expected_adjustment_.load(memory_order_relaxed);
  105. __expected_adjustment_.store(0, memory_order_relaxed);
  106. __phase_.store(__old_phase + 2, memory_order_release);
  107. __phase_.notify_all();
  108. }
  109. return __old_phase;
  110. }
  111. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void wait(arrival_token&& __old_phase) const {
  112. auto const __test_fn = [this, __old_phase]() -> bool { return __phase_.load(memory_order_acquire) != __old_phase; };
  113. std::__libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy());
  114. }
  115. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void arrive_and_drop() {
  116. __expected_adjustment_.fetch_sub(1, memory_order_relaxed);
  117. (void)arrive(1);
  118. }
  119. };
  120. # else
  121. /*
  122. The alternative implementation of __barrier_base is a central barrier.
  123. Two versions of this algorithm are provided:
  124. 1. A fairly straightforward implementation of the litterature for the
  125. general case where the completion function is not empty.
  126. 2. An optimized implementation that exploits 2's complement arithmetic
  127. and well-defined overflow in atomic arithmetic, to handle the phase
  128. roll-over for free.
  129. */
  130. template <class _CompletionF>
  131. class __barrier_base {
  132. __atomic_base<ptrdiff_t> __expected;
  133. __atomic_base<ptrdiff_t> __arrived;
  134. _CompletionF __completion;
  135. __atomic_base<bool> __phase;
  136. public:
  137. using arrival_token = bool;
  138. static constexpr ptrdiff_t max() noexcept { return numeric_limits<ptrdiff_t>::max(); }
  139. _LIBCPP_HIDE_FROM_ABI __barrier_base(ptrdiff_t __expected, _CompletionF __completion = _CompletionF())
  140. : __expected(__expected), __arrived(__expected), __completion(std::move(__completion)), __phase(false) {}
  141. [[nodiscard]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI arrival_token arrive(ptrdiff_t update) {
  142. auto const __old_phase = __phase.load(memory_order_relaxed);
  143. auto const __result = __arrived.fetch_sub(update, memory_order_acq_rel) - update;
  144. auto const new_expected = __expected.load(memory_order_relaxed);
  145. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
  146. update <= new_expected, "update is greater than the expected count for the current barrier phase");
  147. if (0 == __result) {
  148. __completion();
  149. __arrived.store(new_expected, memory_order_relaxed);
  150. __phase.store(!__old_phase, memory_order_release);
  151. __phase.notify_all();
  152. }
  153. return __old_phase;
  154. }
  155. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void wait(arrival_token&& __old_phase) const {
  156. __phase.wait(__old_phase, memory_order_acquire);
  157. }
  158. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void arrive_and_drop() {
  159. __expected.fetch_sub(1, memory_order_relaxed);
  160. (void)arrive(1);
  161. }
  162. };
  163. template <>
  164. class __barrier_base<__empty_completion> {
  165. static constexpr uint64_t __expected_unit = 1ull;
  166. static constexpr uint64_t __arrived_unit = 1ull << 32;
  167. static constexpr uint64_t __expected_mask = __arrived_unit - 1;
  168. static constexpr uint64_t __phase_bit = 1ull << 63;
  169. static constexpr uint64_t __arrived_mask = (__phase_bit - 1) & ~__expected_mask;
  170. __atomic_base<uint64_t> __phase_arrived_expected;
  171. static _LIBCPP_HIDE_FROM_ABI constexpr uint64_t __init(ptrdiff_t __count) _NOEXCEPT {
  172. return ((uint64_t(1u << 31) - __count) << 32) | (uint64_t(1u << 31) - __count);
  173. }
  174. public:
  175. using arrival_token = uint64_t;
  176. static constexpr ptrdiff_t max() noexcept { return ptrdiff_t(1u << 31) - 1; }
  177. _LIBCPP_HIDE_FROM_ABI explicit inline __barrier_base(ptrdiff_t __count, __empty_completion = __empty_completion())
  178. : __phase_arrived_expected(__init(__count)) {}
  179. [[nodiscard]] inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI arrival_token arrive(ptrdiff_t update) {
  180. auto const __inc = __arrived_unit * update;
  181. auto const __old = __phase_arrived_expected.fetch_add(__inc, memory_order_acq_rel);
  182. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
  183. update <= __old, "update is greater than the expected count for the current barrier phase");
  184. if ((__old ^ (__old + __inc)) & __phase_bit) {
  185. __phase_arrived_expected.fetch_add((__old & __expected_mask) << 32, memory_order_relaxed);
  186. __phase_arrived_expected.notify_all();
  187. }
  188. return __old & __phase_bit;
  189. }
  190. inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void wait(arrival_token&& __phase) const {
  191. auto const __test_fn = [=]() -> bool {
  192. uint64_t const __current = __phase_arrived_expected.load(memory_order_acquire);
  193. return ((__current & __phase_bit) != __phase);
  194. };
  195. __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy());
  196. }
  197. inline _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void arrive_and_drop() {
  198. __phase_arrived_expected.fetch_add(__expected_unit, memory_order_relaxed);
  199. (void)arrive(1);
  200. }
  201. };
  202. # endif // !_LIBCPP_HAS_NO_TREE_BARRIER
  203. template <class _CompletionF = __empty_completion>
  204. class barrier {
  205. __barrier_base<_CompletionF> __b_;
  206. public:
  207. using arrival_token = typename __barrier_base<_CompletionF>::arrival_token;
  208. static _LIBCPP_HIDE_FROM_ABI constexpr ptrdiff_t max() noexcept { return __barrier_base<_CompletionF>::max(); }
  209. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI explicit barrier(
  210. ptrdiff_t __count, _CompletionF __completion = _CompletionF())
  211. : __b_(__count, std::move(__completion)) {
  212. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
  213. __count >= 0,
  214. "barrier::barrier(ptrdiff_t, CompletionFunction): barrier cannot be initialized with a negative value");
  215. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
  216. __count <= max(),
  217. "barrier::barrier(ptrdiff_t, CompletionFunction): barrier cannot be initialized with "
  218. "a value greater than max()");
  219. }
  220. barrier(barrier const&) = delete;
  221. barrier& operator=(barrier const&) = delete;
  222. [[__nodiscard__]] _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI arrival_token arrive(ptrdiff_t __update = 1) {
  223. _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(__update > 0, "barrier:arrive must be called with a value greater than 0");
  224. return __b_.arrive(__update);
  225. }
  226. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void wait(arrival_token&& __phase) const {
  227. __b_.wait(std::move(__phase));
  228. }
  229. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void arrive_and_wait() { wait(arrive()); }
  230. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void arrive_and_drop() { __b_.arrive_and_drop(); }
  231. };
  232. _LIBCPP_END_NAMESPACE_STD
  233. #endif // _LIBCPP_STD_VER >= 14
  234. _LIBCPP_POP_MACROS
  235. #if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
  236. # include <atomic>
  237. # include <concepts>
  238. # include <iterator>
  239. # include <memory>
  240. # include <stdexcept>
  241. # include <variant>
  242. #endif
  243. #endif //_LIBCPP_BARRIER