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