call_once.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: call_once.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file provides an Abseil version of `std::call_once` for invoking
  20. // a given function at most once, across all threads. This Abseil version is
  21. // faster than the C++11 version and incorporates the C++17 argument-passing
  22. // fix, so that (for example) non-const references may be passed to the invoked
  23. // function.
  24. #ifndef Y_ABSL_BASE_CALL_ONCE_H_
  25. #define Y_ABSL_BASE_CALL_ONCE_H_
  26. #include <algorithm>
  27. #include <atomic>
  28. #include <cstdint>
  29. #include <type_traits>
  30. #include <utility>
  31. #include "y_absl/base/internal/invoke.h"
  32. #include "y_absl/base/internal/low_level_scheduling.h"
  33. #include "y_absl/base/internal/raw_logging.h"
  34. #include "y_absl/base/internal/scheduling_mode.h"
  35. #include "y_absl/base/internal/spinlock_wait.h"
  36. #include "y_absl/base/macros.h"
  37. #include "y_absl/base/optimization.h"
  38. #include "y_absl/base/port.h"
  39. namespace y_absl {
  40. Y_ABSL_NAMESPACE_BEGIN
  41. class once_flag;
  42. namespace base_internal {
  43. std::atomic<uint32_t>* ControlWord(y_absl::once_flag* flag);
  44. } // namespace base_internal
  45. // call_once()
  46. //
  47. // For all invocations using a given `once_flag`, invokes a given `fn` exactly
  48. // once across all threads. The first call to `call_once()` with a particular
  49. // `once_flag` argument (that does not throw an exception) will run the
  50. // specified function with the provided `args`; other calls with the same
  51. // `once_flag` argument will not run the function, but will wait
  52. // for the provided function to finish running (if it is still running).
  53. //
  54. // This mechanism provides a safe, simple, and fast mechanism for one-time
  55. // initialization in a multi-threaded process.
  56. //
  57. // Example:
  58. //
  59. // class MyInitClass {
  60. // public:
  61. // ...
  62. // mutable y_absl::once_flag once_;
  63. //
  64. // MyInitClass* init() const {
  65. // y_absl::call_once(once_, &MyInitClass::Init, this);
  66. // return ptr_;
  67. // }
  68. //
  69. template <typename Callable, typename... Args>
  70. void call_once(y_absl::once_flag& flag, Callable&& fn, Args&&... args);
  71. // once_flag
  72. //
  73. // Objects of this type are used to distinguish calls to `call_once()` and
  74. // ensure the provided function is only invoked once across all threads. This
  75. // type is not copyable or movable. However, it has a `constexpr`
  76. // constructor, and is safe to use as a namespace-scoped global variable.
  77. class once_flag {
  78. public:
  79. constexpr once_flag() : control_(0) {}
  80. once_flag(const once_flag&) = delete;
  81. once_flag& operator=(const once_flag&) = delete;
  82. private:
  83. friend std::atomic<uint32_t>* base_internal::ControlWord(once_flag* flag);
  84. std::atomic<uint32_t> control_;
  85. };
  86. //------------------------------------------------------------------------------
  87. // End of public interfaces.
  88. // Implementation details follow.
  89. //------------------------------------------------------------------------------
  90. namespace base_internal {
  91. // Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
  92. // initialize entities used by the scheduler implementation.
  93. template <typename Callable, typename... Args>
  94. void LowLevelCallOnce(y_absl::once_flag* flag, Callable&& fn, Args&&... args);
  95. // Disables scheduling while on stack when scheduling mode is non-cooperative.
  96. // No effect for cooperative scheduling modes.
  97. class SchedulingHelper {
  98. public:
  99. explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
  100. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
  101. guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
  102. }
  103. }
  104. ~SchedulingHelper() {
  105. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
  106. base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
  107. }
  108. }
  109. private:
  110. base_internal::SchedulingMode mode_;
  111. bool guard_result_ = false;
  112. };
  113. // Bit patterns for call_once state machine values. Internal implementation
  114. // detail, not for use by clients.
  115. //
  116. // The bit patterns are arbitrarily chosen from unlikely values, to aid in
  117. // debugging. However, kOnceInit must be 0, so that a zero-initialized
  118. // once_flag will be valid for immediate use.
  119. enum {
  120. kOnceInit = 0,
  121. kOnceRunning = 0x65C2937B,
  122. kOnceWaiter = 0x05A308D2,
  123. // A very small constant is chosen for kOnceDone so that it fit in a single
  124. // compare with immediate instruction for most common ISAs. This is verified
  125. // for x86, POWER and ARM.
  126. kOnceDone = 221, // Random Number
  127. };
  128. template <typename Callable, typename... Args>
  129. Y_ABSL_ATTRIBUTE_NOINLINE
  130. void CallOnceImpl(std::atomic<uint32_t>* control,
  131. base_internal::SchedulingMode scheduling_mode, Callable&& fn,
  132. Args&&... args) {
  133. #ifndef NDEBUG
  134. {
  135. uint32_t old_control = control->load(std::memory_order_relaxed);
  136. if (old_control != kOnceInit &&
  137. old_control != kOnceRunning &&
  138. old_control != kOnceWaiter &&
  139. old_control != kOnceDone) {
  140. Y_ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
  141. static_cast<unsigned long>(old_control)); // NOLINT
  142. }
  143. }
  144. #endif // NDEBUG
  145. static const base_internal::SpinLockWaitTransition trans[] = {
  146. {kOnceInit, kOnceRunning, true},
  147. {kOnceRunning, kOnceWaiter, false},
  148. {kOnceDone, kOnceDone, true}};
  149. // Must do this before potentially modifying control word's state.
  150. base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
  151. // Short circuit the simplest case to avoid procedure call overhead.
  152. // The base_internal::SpinLockWait() call returns either kOnceInit or
  153. // kOnceDone. If it returns kOnceDone, it must have loaded the control word
  154. // with std::memory_order_acquire and seen a value of kOnceDone.
  155. uint32_t old_control = kOnceInit;
  156. if (control->compare_exchange_strong(old_control, kOnceRunning,
  157. std::memory_order_relaxed) ||
  158. base_internal::SpinLockWait(control, Y_ABSL_ARRAYSIZE(trans), trans,
  159. scheduling_mode) == kOnceInit) {
  160. base_internal::invoke(std::forward<Callable>(fn),
  161. std::forward<Args>(args)...);
  162. old_control =
  163. control->exchange(base_internal::kOnceDone, std::memory_order_release);
  164. if (old_control == base_internal::kOnceWaiter) {
  165. base_internal::SpinLockWake(control, true);
  166. }
  167. } // else *control is already kOnceDone
  168. }
  169. inline std::atomic<uint32_t>* ControlWord(once_flag* flag) {
  170. return &flag->control_;
  171. }
  172. template <typename Callable, typename... Args>
  173. void LowLevelCallOnce(y_absl::once_flag* flag, Callable&& fn, Args&&... args) {
  174. std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
  175. uint32_t s = once->load(std::memory_order_acquire);
  176. if (Y_ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
  177. base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
  178. std::forward<Callable>(fn),
  179. std::forward<Args>(args)...);
  180. }
  181. }
  182. } // namespace base_internal
  183. template <typename Callable, typename... Args>
  184. void call_once(y_absl::once_flag& flag, Callable&& fn, Args&&... args) {
  185. std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
  186. uint32_t s = once->load(std::memory_order_acquire);
  187. if (Y_ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
  188. base_internal::CallOnceImpl(
  189. once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
  190. std::forward<Callable>(fn), std::forward<Args>(args)...);
  191. }
  192. }
  193. Y_ABSL_NAMESPACE_END
  194. } // namespace y_absl
  195. #endif // Y_ABSL_BASE_CALL_ONCE_H_