call_once.h 8.2 KB

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