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