You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

call_once.h 9.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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/optimization.h"
  38. #include "absl/base/port.h"
  39. namespace absl
  40. {
  41. ABSL_NAMESPACE_BEGIN
  42. class once_flag;
  43. namespace base_internal
  44. {
  45. std::atomic<uint32_t>* ControlWord(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. {
  81. public:
  82. constexpr once_flag() :
  83. control_(0)
  84. {
  85. }
  86. once_flag(const once_flag&) = delete;
  87. once_flag& operator=(const once_flag&) = delete;
  88. private:
  89. friend std::atomic<uint32_t>* base_internal::ControlWord(once_flag* flag);
  90. std::atomic<uint32_t> control_;
  91. };
  92. //------------------------------------------------------------------------------
  93. // End of public interfaces.
  94. // Implementation details follow.
  95. //------------------------------------------------------------------------------
  96. namespace base_internal
  97. {
  98. // Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
  99. // initialize entities used by the scheduler implementation.
  100. template<typename Callable, typename... Args>
  101. void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args);
  102. // Disables scheduling while on stack when scheduling mode is non-cooperative.
  103. // No effect for cooperative scheduling modes.
  104. class SchedulingHelper
  105. {
  106. public:
  107. explicit SchedulingHelper(base_internal::SchedulingMode mode) :
  108. mode_(mode)
  109. {
  110. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY)
  111. {
  112. guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
  113. }
  114. }
  115. ~SchedulingHelper()
  116. {
  117. if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY)
  118. {
  119. base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
  120. }
  121. }
  122. private:
  123. base_internal::SchedulingMode mode_;
  124. bool guard_result_;
  125. };
  126. // Bit patterns for call_once state machine values. Internal implementation
  127. // detail, not for use by clients.
  128. //
  129. // The bit patterns are arbitrarily chosen from unlikely values, to aid in
  130. // debugging. However, kOnceInit must be 0, so that a zero-initialized
  131. // once_flag will be valid for immediate use.
  132. enum
  133. {
  134. kOnceInit = 0,
  135. kOnceRunning = 0x65C2937B,
  136. kOnceWaiter = 0x05A308D2,
  137. // A very small constant is chosen for kOnceDone so that it fit in a single
  138. // compare with immediate instruction for most common ISAs. This is verified
  139. // for x86, POWER and ARM.
  140. kOnceDone = 221, // Random Number
  141. };
  142. template<typename Callable, typename... Args>
  143. ABSL_ATTRIBUTE_NOINLINE void CallOnceImpl(std::atomic<uint32_t>* control, base_internal::SchedulingMode scheduling_mode, Callable&& fn, Args&&... args)
  144. {
  145. #ifndef NDEBUG
  146. {
  147. uint32_t old_control = control->load(std::memory_order_relaxed);
  148. if (old_control != kOnceInit &&
  149. old_control != kOnceRunning &&
  150. old_control != kOnceWaiter &&
  151. old_control != kOnceDone)
  152. {
  153. ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
  154. static_cast<unsigned long>(old_control)); // NOLINT
  155. }
  156. }
  157. #endif // NDEBUG
  158. static const base_internal::SpinLockWaitTransition trans[] = {
  159. {kOnceInit, kOnceRunning, true},
  160. {kOnceRunning, kOnceWaiter, false},
  161. {kOnceDone, kOnceDone, true}};
  162. // Must do this before potentially modifying control word's state.
  163. base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
  164. // Short circuit the simplest case to avoid procedure call overhead.
  165. // The base_internal::SpinLockWait() call returns either kOnceInit or
  166. // kOnceDone. If it returns kOnceDone, it must have loaded the control word
  167. // with std::memory_order_acquire and seen a value of kOnceDone.
  168. uint32_t old_control = kOnceInit;
  169. if (control->compare_exchange_strong(old_control, kOnceRunning, std::memory_order_relaxed) ||
  170. base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans, scheduling_mode) == kOnceInit)
  171. {
  172. base_internal::invoke(std::forward<Callable>(fn), std::forward<Args>(args)...);
  173. old_control =
  174. control->exchange(base_internal::kOnceDone, std::memory_order_release);
  175. if (old_control == base_internal::kOnceWaiter)
  176. {
  177. base_internal::SpinLockWake(control, true);
  178. }
  179. } // else *control is already kOnceDone
  180. }
  181. inline std::atomic<uint32_t>* ControlWord(once_flag* flag)
  182. {
  183. return &flag->control_;
  184. }
  185. template<typename Callable, typename... Args>
  186. void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args)
  187. {
  188. std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
  189. uint32_t s = once->load(std::memory_order_acquire);
  190. if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone))
  191. {
  192. base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY, std::forward<Callable>(fn), std::forward<Args>(args)...);
  193. }
  194. }
  195. } // namespace base_internal
  196. template<typename Callable, typename... Args>
  197. void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args)
  198. {
  199. std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
  200. uint32_t s = once->load(std::memory_order_acquire);
  201. if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone))
  202. {
  203. base_internal::CallOnceImpl(
  204. once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL, std::forward<Callable>(fn), std::forward<Args>(args)...
  205. );
  206. }
  207. }
  208. ABSL_NAMESPACE_END
  209. } // namespace absl
  210. #endif // ABSL_BASE_CALL_ONCE_H_