call_once.h
Go to the documentation of this file.
00001 // Copyright 2017 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 //
00015 // -----------------------------------------------------------------------------
00016 // File: call_once.h
00017 // -----------------------------------------------------------------------------
00018 //
00019 // This header file provides an Abseil version of `std::call_once` for invoking
00020 // a given function at most once, across all threads. This Abseil version is
00021 // faster than the C++11 version and incorporates the C++17 argument-passing
00022 // fix, so that (for example) non-const references may be passed to the invoked
00023 // function.
00024 
00025 #ifndef ABSL_BASE_CALL_ONCE_H_
00026 #define ABSL_BASE_CALL_ONCE_H_
00027 
00028 #include <algorithm>
00029 #include <atomic>
00030 #include <cstdint>
00031 #include <type_traits>
00032 #include <utility>
00033 
00034 #include "absl/base/internal/invoke.h"
00035 #include "absl/base/internal/low_level_scheduling.h"
00036 #include "absl/base/internal/raw_logging.h"
00037 #include "absl/base/internal/scheduling_mode.h"
00038 #include "absl/base/internal/spinlock_wait.h"
00039 #include "absl/base/macros.h"
00040 #include "absl/base/optimization.h"
00041 #include "absl/base/port.h"
00042 
00043 namespace absl {
00044 
00045 class once_flag;
00046 
00047 namespace base_internal {
00048 std::atomic<uint32_t>* ControlWord(absl::once_flag* flag);
00049 }  // namespace base_internal
00050 
00051 // call_once()
00052 //
00053 // For all invocations using a given `once_flag`, invokes a given `fn` exactly
00054 // once across all threads. The first call to `call_once()` with a particular
00055 // `once_flag` argument (that does not throw an exception) will run the
00056 // specified function with the provided `args`; other calls with the same
00057 // `once_flag` argument will not run the function, but will wait
00058 // for the provided function to finish running (if it is still running).
00059 //
00060 // This mechanism provides a safe, simple, and fast mechanism for one-time
00061 // initialization in a multi-threaded process.
00062 //
00063 // Example:
00064 //
00065 // class MyInitClass {
00066 //  public:
00067 //  ...
00068 //  mutable absl::once_flag once_;
00069 //
00070 //  MyInitClass* init() const {
00071 //    absl::call_once(once_, &MyInitClass::Init, this);
00072 //    return ptr_;
00073 //  }
00074 //
00075 template <typename Callable, typename... Args>
00076 void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
00077 
00078 // once_flag
00079 //
00080 // Objects of this type are used to distinguish calls to `call_once()` and
00081 // ensure the provided function is only invoked once across all threads. This
00082 // type is not copyable or movable. However, it has a `constexpr`
00083 // constructor, and is safe to use as a namespace-scoped global variable.
00084 class once_flag {
00085  public:
00086   constexpr once_flag() : control_(0) {}
00087   once_flag(const once_flag&) = delete;
00088   once_flag& operator=(const once_flag&) = delete;
00089 
00090  private:
00091   friend std::atomic<uint32_t>* base_internal::ControlWord(once_flag* flag);
00092   std::atomic<uint32_t> control_;
00093 };
00094 
00095 //------------------------------------------------------------------------------
00096 // End of public interfaces.
00097 // Implementation details follow.
00098 //------------------------------------------------------------------------------
00099 
00100 namespace base_internal {
00101 
00102 // Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
00103 // initialize entities used by the scheduler implementation.
00104 template <typename Callable, typename... Args>
00105 void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args);
00106 
00107 // Disables scheduling while on stack when scheduling mode is non-cooperative.
00108 // No effect for cooperative scheduling modes.
00109 class SchedulingHelper {
00110  public:
00111   explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
00112     if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
00113       guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
00114     }
00115   }
00116 
00117   ~SchedulingHelper() {
00118     if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
00119       base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
00120     }
00121   }
00122 
00123  private:
00124   base_internal::SchedulingMode mode_;
00125   bool guard_result_;
00126 };
00127 
00128 // Bit patterns for call_once state machine values.  Internal implementation
00129 // detail, not for use by clients.
00130 //
00131 // The bit patterns are arbitrarily chosen from unlikely values, to aid in
00132 // debugging.  However, kOnceInit must be 0, so that a zero-initialized
00133 // once_flag will be valid for immediate use.
00134 enum {
00135   kOnceInit = 0,
00136   kOnceRunning = 0x65C2937B,
00137   kOnceWaiter = 0x05A308D2,
00138   // A very small constant is chosen for kOnceDone so that it fit in a single
00139   // compare with immediate instruction for most common ISAs.  This is verified
00140   // for x86, POWER and ARM.
00141   kOnceDone = 221,    // Random Number
00142 };
00143 
00144 template <typename Callable, typename... Args>
00145 void CallOnceImpl(std::atomic<uint32_t>* control,
00146                   base_internal::SchedulingMode scheduling_mode, Callable&& fn,
00147                   Args&&... args) {
00148 #ifndef NDEBUG
00149   {
00150     uint32_t old_control = control->load(std::memory_order_acquire);
00151     if (old_control != kOnceInit &&
00152         old_control != kOnceRunning &&
00153         old_control != kOnceWaiter &&
00154         old_control != kOnceDone) {
00155       ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
00156                    static_cast<unsigned long>(old_control));  // NOLINT
00157     }
00158   }
00159 #endif  // NDEBUG
00160   static const base_internal::SpinLockWaitTransition trans[] = {
00161       {kOnceInit, kOnceRunning, true},
00162       {kOnceRunning, kOnceWaiter, false},
00163       {kOnceDone, kOnceDone, true}};
00164 
00165   // Must do this before potentially modifying control word's state.
00166   base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
00167   // Short circuit the simplest case to avoid procedure call overhead.
00168   uint32_t old_control = kOnceInit;
00169   if (control->compare_exchange_strong(old_control, kOnceRunning,
00170                                        std::memory_order_acquire,
00171                                        std::memory_order_relaxed) ||
00172       base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
00173                                   scheduling_mode) == kOnceInit) {
00174     base_internal::Invoke(std::forward<Callable>(fn),
00175                           std::forward<Args>(args)...);
00176     old_control = control->load(std::memory_order_relaxed);
00177     control->store(base_internal::kOnceDone, std::memory_order_release);
00178     if (old_control == base_internal::kOnceWaiter) {
00179       base_internal::SpinLockWake(control, true);
00180     }
00181   }  // else *control is already kOnceDone
00182 }
00183 
00184 inline std::atomic<uint32_t>* ControlWord(once_flag* flag) {
00185   return &flag->control_;
00186 }
00187 
00188 template <typename Callable, typename... Args>
00189 void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args) {
00190   std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
00191   uint32_t s = once->load(std::memory_order_acquire);
00192   if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
00193     base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
00194                                 std::forward<Callable>(fn),
00195                                 std::forward<Args>(args)...);
00196   }
00197 }
00198 
00199 }  // namespace base_internal
00200 
00201 template <typename Callable, typename... Args>
00202 void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
00203   std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
00204   uint32_t s = once->load(std::memory_order_acquire);
00205   if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
00206     base_internal::CallOnceImpl(
00207         once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
00208         std::forward<Callable>(fn), std::forward<Args>(args)...);
00209   }
00210 }
00211 
00212 }  // namespace absl
00213 
00214 #endif  // ABSL_BASE_CALL_ONCE_H_


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:14