semaphore 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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_SEMAPHORE
  10. #define _LIBCPP_SEMAPHORE
  11. /*
  12. semaphore synopsis
  13. namespace std {
  14. template<ptrdiff_t least_max_value = implementation-defined>
  15. class counting_semaphore
  16. {
  17. public:
  18. static constexpr ptrdiff_t max() noexcept;
  19. constexpr explicit counting_semaphore(ptrdiff_t desired);
  20. ~counting_semaphore();
  21. counting_semaphore(const counting_semaphore&) = delete;
  22. counting_semaphore& operator=(const counting_semaphore&) = delete;
  23. void release(ptrdiff_t update = 1);
  24. void acquire();
  25. bool try_acquire() noexcept;
  26. template<class Rep, class Period>
  27. bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time);
  28. template<class Clock, class Duration>
  29. bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time);
  30. private:
  31. ptrdiff_t counter; // exposition only
  32. };
  33. using binary_semaphore = counting_semaphore<1>;
  34. }
  35. */
  36. #include <__assert> // all public C++ headers provide the assertion handler
  37. #include <__atomic/atomic_base.h>
  38. #include <__atomic/atomic_sync.h>
  39. #include <__atomic/memory_order.h>
  40. #include <__availability>
  41. #include <__chrono/time_point.h>
  42. #include <__config>
  43. #include <__thread/poll_with_backoff.h>
  44. #include <__thread/timed_backoff_policy.h>
  45. #include <__threading_support>
  46. #include <cstddef>
  47. #include <limits>
  48. #include <version>
  49. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  50. # pragma GCC system_header
  51. #endif
  52. #ifdef _LIBCPP_HAS_NO_THREADS
  53. # error "<semaphore> is not supported since libc++ has been configured without support for threads."
  54. #endif
  55. _LIBCPP_PUSH_MACROS
  56. #include <__undef_macros>
  57. #if _LIBCPP_STD_VER >= 14
  58. _LIBCPP_BEGIN_NAMESPACE_STD
  59. /*
  60. __atomic_semaphore_base is the general-case implementation.
  61. It is a typical Dijkstra semaphore algorithm over atomics, wait and notify
  62. functions. It avoids contention against users' own use of those facilities.
  63. */
  64. #define _LIBCPP_SEMAPHORE_MAX (numeric_limits<ptrdiff_t>::max())
  65. class __atomic_semaphore_base
  66. {
  67. __atomic_base<ptrdiff_t> __a_;
  68. public:
  69. _LIBCPP_INLINE_VISIBILITY
  70. constexpr explicit __atomic_semaphore_base(ptrdiff_t __count) : __a_(__count)
  71. {
  72. }
  73. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  74. void release(ptrdiff_t __update = 1)
  75. {
  76. auto __old = __a_.fetch_add(__update, memory_order_release);
  77. _LIBCPP_ASSERT_UNCATEGORIZED(__update <= _LIBCPP_SEMAPHORE_MAX - __old, "update is greater than the expected value");
  78. if (__old > 0)
  79. {
  80. // Nothing to do
  81. }
  82. else if (__update > 1)
  83. __a_.notify_all();
  84. else
  85. __a_.notify_one();
  86. }
  87. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  88. void acquire()
  89. {
  90. auto const __test_fn = [this]() -> bool {
  91. auto __old = __a_.load(memory_order_relaxed);
  92. return (__old != 0) && __a_.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
  93. };
  94. __cxx_atomic_wait(&__a_.__a_, __test_fn);
  95. }
  96. template <class _Rep, class _Period>
  97. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  98. bool try_acquire_for(chrono::duration<_Rep, _Period> const& __rel_time)
  99. {
  100. if (__rel_time == chrono::duration<_Rep, _Period>::zero())
  101. return try_acquire();
  102. auto const __test_fn = [this]() { return try_acquire(); };
  103. return std::__libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy(), __rel_time);
  104. }
  105. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  106. bool try_acquire()
  107. {
  108. auto __old = __a_.load(memory_order_acquire);
  109. while (true) {
  110. if (__old == 0)
  111. return false;
  112. if (__a_.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed))
  113. return true;
  114. }
  115. }
  116. };
  117. template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
  118. class counting_semaphore
  119. {
  120. __atomic_semaphore_base __semaphore_;
  121. public:
  122. static_assert(__least_max_value >= 0, "The least maximum value must be a positive number");
  123. static constexpr ptrdiff_t max() noexcept {
  124. return __least_max_value;
  125. }
  126. _LIBCPP_INLINE_VISIBILITY
  127. constexpr explicit counting_semaphore(ptrdiff_t __count) : __semaphore_(__count)
  128. {
  129. _LIBCPP_ASSERT_UNCATEGORIZED(
  130. __count >= 0,
  131. "counting_semaphore::counting_semaphore(ptrdiff_t): counting_semaphore cannot be "
  132. "initialized with a negative value");
  133. _LIBCPP_ASSERT_UNCATEGORIZED(
  134. __count <= max(),
  135. "counting_semaphore::counting_semaphore(ptrdiff_t): counting_semaphore cannot be "
  136. "initialized with a value greater than max()");
  137. }
  138. ~counting_semaphore() = default;
  139. counting_semaphore(const counting_semaphore&) = delete;
  140. counting_semaphore& operator=(const counting_semaphore&) = delete;
  141. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  142. void release(ptrdiff_t __update = 1)
  143. {
  144. _LIBCPP_ASSERT_UNCATEGORIZED(__update >= 0, "counting_semaphore:release called with a negative value");
  145. __semaphore_.release(__update);
  146. }
  147. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  148. void acquire()
  149. {
  150. __semaphore_.acquire();
  151. }
  152. template<class _Rep, class _Period>
  153. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  154. bool try_acquire_for(chrono::duration<_Rep, _Period> const& __rel_time)
  155. {
  156. return __semaphore_.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
  157. }
  158. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  159. bool try_acquire()
  160. {
  161. return __semaphore_.try_acquire();
  162. }
  163. template <class _Clock, class _Duration>
  164. _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
  165. bool try_acquire_until(chrono::time_point<_Clock, _Duration> const& __abs_time)
  166. {
  167. auto const __current = _Clock::now();
  168. if (__current >= __abs_time)
  169. return try_acquire();
  170. else
  171. return try_acquire_for(__abs_time - __current);
  172. }
  173. };
  174. using binary_semaphore = counting_semaphore<1>;
  175. _LIBCPP_END_NAMESPACE_STD
  176. #endif // _LIBCPP_STD_VER >= 14
  177. _LIBCPP_POP_MACROS
  178. #if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
  179. # include <atomic>
  180. #endif
  181. #endif //_LIBCPP_SEMAPHORE