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>
45 constexpr once_flag() noexcept = default;
46 once_flag(const once_flag&) = delete;
47 once_flag& operator=(const once_flag&) = delete;
49 template <typename Callable, class... Args>
50 friend void call_once(once_flag& flag, Callable&& f, Args&&... args);
51 template <typename Callable, class... Args>
52 friend void call_once_impl_no_inline(once_flag& flag,
57 std::atomic<bool> called_{false};
58 folly::SharedMutex mutex_;
61 template <class Callable, class... Args>
62 void FOLLY_ALWAYS_INLINE
63 call_once(once_flag& flag, Callable&& f, Args&&... args) {
64 if (LIKELY(flag.called_.load(std::memory_order_acquire))) {
67 call_once_impl_no_inline(
68 flag, std::forward<Callable>(f), std::forward<Args>(args)...);
71 // Implementation detail: out-of-line slow path
72 template <class Callable, class... Args>
74 call_once_impl_no_inline(once_flag& flag, Callable&& f, Args&&... args) {
75 std::lock_guard<folly::SharedMutex> lg(flag.mutex_);
80 std::forward<Callable>(f)(std::forward<Args>(args)...);
82 flag.called_.store(true, std::memory_order_release);