2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Drop-in replacement for std::call_once() with a fast path, which the GCC
19 * implementation lacks. The tradeoff is a slightly larger `once_flag' struct
20 * (8 bytes vs 4 bytes with GCC on Linux/x64).
22 * $ call_once_test --benchmark --bm_min_iters=100000000 --threads=16
23 * ============================================================================
24 * folly/test/CallOnceTest.cpp relative time/iter iters/s
25 * ============================================================================
26 * StdCallOnceBench 3.54ns 282.82M
27 * FollyCallOnceBench 698.48ps 1.43G
28 * ============================================================================
37 #include <folly/Likely.h>
38 #include <folly/Portability.h>
39 #include <folly/SharedMutex.h>
43 template <typename Mutex>
46 // Implementation detail: out-of-line slow path
47 template <class Mutex, class Callable, class... Args>
48 void FOLLY_NOINLINE call_once_impl_no_inline(
49 detail::once_flag<Mutex>& flag,
52 std::lock_guard<Mutex> lg(flag.mutex_);
57 std::forward<Callable>(f)(std::forward<Args>(args)...);
59 flag.called_.store(true, std::memory_order_release);
63 using once_flag = detail::once_flag<folly::SharedMutex>;
65 template <class Mutex, class Callable, class... Args>
66 void FOLLY_ALWAYS_INLINE
67 call_once(detail::once_flag<Mutex>& flag, Callable&& f, Args&&... args) {
68 if (LIKELY(flag.called_.load(std::memory_order_acquire))) {
71 call_once_impl_no_inline(
72 flag, std::forward<Callable>(f), std::forward<Args>(args)...);
77 template <typename Mutex>
80 constexpr once_flag() noexcept = default;
81 once_flag(const once_flag&) = delete;
82 once_flag& operator=(const once_flag&) = delete;
84 template <typename Mutex_, typename Callable, class... Args>
85 friend void ::folly::call_once(
86 detail::once_flag<Mutex_>& flag,
89 template <typename Mutex_, typename Callable, class... Args>
90 friend void call_once_impl_no_inline(
91 detail::once_flag<Mutex_>& flag,
96 std::atomic<bool> called_{false};