call_once.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 ABSL_BASE_CALL_ONCE_H_
  25. #define ABSL_BASE_CALL_ONCE_H_
  26. #include <algorithm>
  27. #include <atomic>
  28. #include <cstdint>
  29. #include <type_traits>
  30. #include <utility>
  31. #include "absl/base/internal/invoke.h"
  32. #include "absl/base/internal/low_level_scheduling.h"
  33. #include "absl/base/internal/raw_logging.h"
  34. #include "absl/base/internal/scheduling_mode.h"
  35. #include "absl/base/internal/spinlock_wait.h"
  36. #include "absl/base/macros.h"
  37. #include "absl/base/nullability.h"
  38. #include "absl/base/optimization.h"
  39. #include "absl/base/port.h"
  40. namespace absl {
  41. ABSL_NAMESPACE_BEGIN
  42. class once_flag;
  43. namespace base_internal {
  44. absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
  45. absl::Nonnull<absl::once_flag*> flag);
  46. } // namespace base_internal
  47. // call_once()
  48. //
  49. // For all invocations using a given `once_flag`, invokes a given `fn` exactly
  50. // once across all threads. The first call to `call_once()` with a particular
  51. // `once_flag` argument (that does not throw an exception) will run the
  52. // specified function with the provided `args`; other calls with the same
  53. // `once_flag` argument will not run the function, but will wait
  54. // for the provided function to finish running (if it is still running).
  55. //
  56. // This mechanism provides a safe, simple, and fast mechanism for one-time
  57. // initialization in a multi-threaded process.
  58. //
  59. // Example:
  60. //
  61. // class MyInitClass {
  62. // public:
  63. // ...
  64. // mutable absl::once_flag once_;
  65. //
  66. // MyInitClass* init() const {
  67. // absl::call_once(once_, &MyInitClass::Init, this);
  68. // return ptr_;
  69. // }
  70. //
  71. template <typename Callable, typename... Args>
  72. void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
  73. // once_flag
  74. //
  75. // Objects of this type are used to distinguish calls to `call_once()` and
  76. // ensure the provided function is only invoked once across all threads. This
  77. // type is not copyable or movable. However, it has a `constexpr`
  78. // constructor, and is safe to use as a namespace-scoped global variable.
  79. class once_flag {
  80. public:
  81. constexpr once_flag() : control_(0) {}
  82. once_flag(const once_flag&) = delete;
  83. once_flag& operator=(const once_flag&) = delete;
  84. private:
  85. friend absl::Nonnull<std::atomic<uint32_t>*> base_internal::ControlWord(
  86. absl::Nonnull<once_flag*> flag);
  87. std::atomic<uint32_t> control_;
  88. };
  89. //------------------------------------------------------------------------------
  90. // End of public interfaces.
  91. // Implementation details follow.
  92. //------------------------------------------------------------------------------
  93. namespace base_internal {
  94. // Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
  95. // initialize entities used by the scheduler implementation.
  96. template <typename Callable, typename... Args>
  97. void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
  98. Args&&... args);
  99. // Disables scheduling while on stack when scheduling mode is non-cooperative.
  100. // No effect for cooperative scheduling modes.
  101. class SchedulingHelper {
  102. public:
  103. explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
  104. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
  105. guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
  106. }
  107. }
  108. ~SchedulingHelper() {
  109. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
  110. base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
  111. }
  112. }
  113. private:
  114. base_internal::SchedulingMode mode_;
  115. bool guard_result_ = false;
  116. };
  117. // Bit patterns for call_once state machine values. Internal implementation
  118. // detail, not for use by clients.
  119. //
  120. // The bit patterns are arbitrarily chosen from unlikely values, to aid in
  121. // debugging. However, kOnceInit must be 0, so that a zero-initialized
  122. // once_flag will be valid for immediate use.
  123. enum {
  124. kOnceInit = 0,
  125. kOnceRunning = 0x65C2937B,
  126. kOnceWaiter = 0x05A308D2,
  127. // A very small constant is chosen for kOnceDone so that it fit in a single
  128. // compare with immediate instruction for most common ISAs. This is verified
  129. // for x86, POWER and ARM.
  130. kOnceDone = 221, // Random Number
  131. };
  132. template <typename Callable, typename... Args>
  133. ABSL_ATTRIBUTE_NOINLINE void CallOnceImpl(
  134. absl::Nonnull<std::atomic<uint32_t>*> control,
  135. base_internal::SchedulingMode scheduling_mode, Callable&& fn,
  136. Args&&... args) {
  137. #ifndef NDEBUG
  138. {
  139. uint32_t old_control = control->load(std::memory_order_relaxed);
  140. if (old_control != kOnceInit &&
  141. old_control != kOnceRunning &&
  142. old_control != kOnceWaiter &&
  143. old_control != kOnceDone) {
  144. ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
  145. static_cast<unsigned long>(old_control)); // NOLINT
  146. }
  147. }
  148. #endif // NDEBUG
  149. static const base_internal::SpinLockWaitTransition trans[] = {
  150. {kOnceInit, kOnceRunning, true},
  151. {kOnceRunning, kOnceWaiter, false},
  152. {kOnceDone, kOnceDone, true}};
  153. // Must do this before potentially modifying control word's state.
  154. base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
  155. // Short circuit the simplest case to avoid procedure call overhead.
  156. // The base_internal::SpinLockWait() call returns either kOnceInit or
  157. // kOnceDone. If it returns kOnceDone, it must have loaded the control word
  158. // with std::memory_order_acquire and seen a value of kOnceDone.
  159. uint32_t old_control = kOnceInit;
  160. if (control->compare_exchange_strong(old_control, kOnceRunning,
  161. std::memory_order_relaxed) ||
  162. base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
  163. scheduling_mode) == kOnceInit) {
  164. base_internal::invoke(std::forward<Callable>(fn),
  165. std::forward<Args>(args)...);
  166. old_control =
  167. control->exchange(base_internal::kOnceDone, std::memory_order_release);
  168. if (old_control == base_internal::kOnceWaiter) {
  169. base_internal::SpinLockWake(control, true);
  170. }
  171. } // else *control is already kOnceDone
  172. }
  173. inline absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
  174. absl::Nonnull<once_flag*> flag) {
  175. return &flag->control_;
  176. }
  177. template <typename Callable, typename... Args>
  178. void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
  179. Args&&... args) {
  180. std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
  181. uint32_t s = once->load(std::memory_order_acquire);
  182. if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
  183. base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
  184. std::forward<Callable>(fn),
  185. std::forward<Args>(args)...);
  186. }
  187. }
  188. } // namespace base_internal
  189. template <typename Callable, typename... Args>
  190. void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
  191. std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
  192. uint32_t s = once->load(std::memory_order_acquire);
  193. if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
  194. base_internal::CallOnceImpl(
  195. once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
  196. std::forward<Callable>(fn), std::forward<Args>(args)...);
  197. }
  198. }
  199. ABSL_NAMESPACE_END
  200. } // namespace absl
  201. #endif // ABSL_BASE_CALL_ONCE_H_