2 * Copyright 2013-present 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.
23 #include <type_traits>
25 #include <boost/noncopyable.hpp>
27 #include <folly/portability/Unistd.h>
29 namespace folly { namespace detail {
31 enum class FutexResult {
32 VALUE_CHANGED, /* Futex value didn't match expected */
33 AWOKEN, /* futex wait matched with a futex wake */
34 INTERRUPTED, /* Spurious wake-up or signal caused futex wait failure */
39 * Futex is an atomic 32 bit unsigned integer that provides access to the
40 * futex() syscall on that value. It is templated in such a way that it
41 * can interact properly with DeterministicSchedule testing.
43 * If you don't know how to use futex(), you probably shouldn't be using
44 * this class. Even if you do know how, you should have a good reason
45 * (and benchmarks to back you up).
47 template <template <typename> class Atom = std::atomic>
48 struct Futex : Atom<uint32_t>, boost::noncopyable {
50 explicit constexpr Futex(uint32_t init = 0) : Atom<uint32_t>(init) {}
52 /** Puts the thread to sleep if this->load() == expected. Returns true when
53 * it is returning because it has consumed a wake() event, false for any
54 * other return (signal, this->load() != expected, or spurious wakeup). */
55 FutexResult futexWait(uint32_t expected, uint32_t waitMask = -1) {
56 auto rv = futexWaitImpl(expected, nullptr, nullptr, waitMask);
57 assert(rv != FutexResult::TIMEDOUT);
61 /** Similar to futexWait but also accepts a deadline until when the wait call
64 * Optimal clock types: std::chrono::system_clock, std::chrono::steady_clock.
65 * NOTE: On some systems steady_clock is just an alias for system_clock,
66 * and is not actually steady.
68 * For any other clock type, now() will be invoked twice. */
69 template <class Clock, class Duration = typename Clock::duration>
70 FutexResult futexWaitUntil(
72 std::chrono::time_point<Clock, Duration> const& deadline,
73 uint32_t waitMask = -1) {
74 using Target = typename std::conditional<
76 std::chrono::steady_clock,
77 std::chrono::system_clock>::type;
78 auto const converted = time_point_conv<Target>(deadline);
79 return futexWaitImpl(expected, converted, waitMask);
82 /** Wakens up to count waiters where (waitMask & wakeMask) !=
83 * 0, returning the number of awoken threads, or -1 if an error
84 * occurred. Note that when constructing a concurrency primitive
85 * that can guard its own destruction, it is likely that you will
86 * want to ignore EINVAL here (as well as making sure that you
87 * never touch the object after performing the memory store that
88 * is the linearization point for unlock or control handoff).
89 * See https://sourceware.org/bugzilla/show_bug.cgi?id=13690 */
90 int futexWake(int count = std::numeric_limits<int>::max(),
91 uint32_t wakeMask = -1);
94 /** Optimal when TargetClock is the same type as Clock.
96 * Otherwise, both Clock::now() and TargetClock::now() must be invoked. */
97 template <typename TargetClock, typename Clock, typename Duration>
98 static typename TargetClock::time_point time_point_conv(
99 std::chrono::time_point<Clock, Duration> const& time) {
100 using std::chrono::duration_cast;
101 using TargetDuration = typename TargetClock::duration;
102 using TargetTimePoint = typename TargetClock::time_point;
103 if (std::is_same<Clock, TargetClock>::value) {
104 // in place of time_point_cast, which cannot compile without if-constexpr
105 auto const delta = time.time_since_epoch();
106 return TargetTimePoint(duration_cast<TargetDuration>(delta));
108 // different clocks with different epochs, so non-optimal case
109 auto const delta = time - Clock::now();
110 return TargetClock::now() + duration_cast<TargetDuration>(delta);
114 template <typename Deadline>
115 typename std::enable_if<Deadline::clock::is_steady, FutexResult>::type
118 Deadline const& deadline,
120 return futexWaitImpl(expected, nullptr, &deadline, waitMask);
123 template <typename Deadline>
124 typename std::enable_if<!Deadline::clock::is_steady, FutexResult>::type
127 Deadline const& deadline,
129 return futexWaitImpl(expected, &deadline, nullptr, waitMask);
132 /** Underlying implementation of futexWait and futexWaitUntil.
133 * At most one of absSystemTime and absSteadyTime should be non-null.
134 * Timeouts are separated into separate parameters to allow the
135 * implementations to be elsewhere without templating on the clock
136 * type, which is otherwise complicated by the fact that steady_clock
137 * is the same as system_clock on some platforms. */
138 FutexResult futexWaitImpl(
140 std::chrono::system_clock::time_point const* absSystemTime,
141 std::chrono::steady_clock::time_point const* absSteadyTime,
145 /** A std::atomic subclass that can be used to force Futex to emulate
146 * the underlying futex() syscall. This is primarily useful to test or
147 * benchmark the emulated implementation on systems that don't need it. */
148 template <typename T>
149 struct EmulatedFutexAtomic : public std::atomic<T> {
150 EmulatedFutexAtomic() noexcept = default;
151 constexpr /* implicit */ EmulatedFutexAtomic(T init) noexcept
152 : std::atomic<T>(init) {}
153 // It doesn't copy or move
154 EmulatedFutexAtomic(EmulatedFutexAtomic&& rhs) = delete;
157 /* Available specializations, with definitions elsewhere */
160 int Futex<std::atomic>::futexWake(int count, uint32_t wakeMask);
163 FutexResult Futex<std::atomic>::futexWaitImpl(
165 std::chrono::system_clock::time_point const* absSystemTime,
166 std::chrono::steady_clock::time_point const* absSteadyTime,
170 int Futex<EmulatedFutexAtomic>::futexWake(int count, uint32_t wakeMask);
173 FutexResult Futex<EmulatedFutexAtomic>::futexWaitImpl(
175 std::chrono::system_clock::time_point const* absSystemTime,
176 std::chrono::steady_clock::time_point const* absSteadyTime,
179 } // namespace detail