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.
17 #include <folly/detail/Futex.h>
18 #include <folly/test/DeterministicSchedule.h>
25 #include <glog/logging.h>
27 #include <folly/Chrono.h>
28 #include <folly/portability/GTest.h>
29 #include <folly/portability/Time.h>
31 using namespace folly::detail;
32 using namespace folly::test;
34 using namespace std::chrono;
35 using folly::chrono::coarse_steady_clock;
37 typedef DeterministicSchedule DSched;
39 template <template <typename> class Atom>
40 void run_basic_thread(
42 EXPECT_EQ(FutexResult::AWOKEN, f.futexWait(0));
45 template <template <typename> class Atom>
46 void run_basic_tests() {
49 EXPECT_EQ(FutexResult::VALUE_CHANGED, f.futexWait(1));
50 EXPECT_EQ(f.futexWake(), 0);
52 auto thr = DSched::thread(std::bind(run_basic_thread<Atom>, std::ref(f)));
54 while (f.futexWake() != 1) {
55 std::this_thread::yield();
61 template <template <typename> class Atom, typename Clock, typename Duration>
62 void liveClockWaitUntilTests() {
65 for (int stress = 0; stress < 1000; ++stress) {
66 auto fp = &f; // workaround for t5336595
67 auto thrA = DSched::thread([fp,stress]{
69 const auto deadline = time_point_cast<Duration>(
70 Clock::now() + microseconds(1 << (stress % 20)));
71 const auto res = fp->futexWaitUntil(0, deadline);
72 EXPECT_TRUE(res == FutexResult::TIMEDOUT || res == FutexResult::AWOKEN);
73 if (res == FutexResult::AWOKEN) {
79 while (f.futexWake() != 1) {
80 std::this_thread::yield();
87 const auto start = Clock::now();
88 const auto deadline = time_point_cast<Duration>(start + milliseconds(100));
89 EXPECT_EQ(f.futexWaitUntil(0, deadline), FutexResult::TIMEDOUT);
90 LOG(INFO) << "Futex wait timed out after waiting for "
91 << duration_cast<milliseconds>(Clock::now() - start).count()
92 << "ms using clock with " << Duration::period::den
93 << " precision, should be ~100ms";
97 const auto start = Clock::now();
98 const auto deadline = time_point_cast<Duration>(
99 start - 2 * start.time_since_epoch());
100 EXPECT_EQ(f.futexWaitUntil(0, deadline), FutexResult::TIMEDOUT);
101 LOG(INFO) << "Futex wait with invalid deadline timed out after waiting for "
102 << duration_cast<milliseconds>(Clock::now() - start).count()
103 << "ms using clock with " << Duration::period::den
104 << " precision, should be ~0ms";
108 template <typename Clock>
109 void deterministicAtomicWaitUntilTests() {
110 Futex<DeterministicAtomic> f(0);
112 // Futex wait must eventually fail with either FutexResult::TIMEDOUT or
113 // FutexResult::INTERRUPTED
114 const auto res = f.futexWaitUntil(0, Clock::now() + milliseconds(100));
115 EXPECT_TRUE(res == FutexResult::TIMEDOUT || res == FutexResult::INTERRUPTED);
118 template <template <typename> class Atom>
119 void run_wait_until_tests() {
120 liveClockWaitUntilTests<Atom, system_clock, system_clock::duration>();
121 liveClockWaitUntilTests<Atom, steady_clock, steady_clock::duration>();
122 liveClockWaitUntilTests<Atom, steady_clock, coarse_steady_clock::duration>();
124 typedef duration<int64_t, std::ratio<1, 10000000>> decimicroseconds;
125 liveClockWaitUntilTests<Atom, system_clock, decimicroseconds>();
129 void run_wait_until_tests<DeterministicAtomic>() {
130 deterministicAtomicWaitUntilTests<system_clock>();
131 deterministicAtomicWaitUntilTests<steady_clock>();
132 deterministicAtomicWaitUntilTests<coarse_steady_clock>();
135 uint64_t diff(uint64_t a, uint64_t b) {
136 return a > b ? a - b : b - a;
139 void run_system_clock_test() {
140 /* Test to verify that system_clock uses clock_gettime(CLOCK_REALTIME, ...)
141 * for the time_points */
143 const int maxIters = 1000;
145 const uint64_t delta = 10000000 /* 10 ms */;
147 /** The following loop is only to make the test more robust in the presence of
148 * clock adjustments that can occur. We just run the loop maxIter times and
149 * expect with very high probability that there will be atleast one iteration
150 * of the test during which clock adjustments > delta have not occurred. */
151 while (iter < maxIters) {
152 uint64_t a = duration_cast<nanoseconds>(system_clock::now()
153 .time_since_epoch()).count();
155 clock_gettime(CLOCK_REALTIME, &ts);
156 uint64_t b = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
158 uint64_t c = duration_cast<nanoseconds>(system_clock::now()
159 .time_since_epoch()).count();
161 if (diff(a, b) <= delta &&
162 diff(b, c) <= delta &&
163 diff(a, c) <= 2 * delta) {
164 /* Success! system_clock uses CLOCK_REALTIME for time_points */
169 EXPECT_TRUE(iter < maxIters);
172 void run_steady_clock_test() {
173 /* Test to verify that steady_clock uses clock_gettime(CLOCK_MONOTONIC, ...)
174 * for the time_points */
175 EXPECT_TRUE(steady_clock::is_steady);
177 const uint64_t A = duration_cast<nanoseconds>(steady_clock::now()
178 .time_since_epoch()).count();
181 clock_gettime(CLOCK_MONOTONIC, &ts);
182 const uint64_t B = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
184 const uint64_t C = duration_cast<nanoseconds>(steady_clock::now()
185 .time_since_epoch()).count();
186 EXPECT_TRUE(A <= B && B <= C);
189 template <template <typename> class Atom>
190 void run_wake_blocked_test() {
191 for (auto delay = std::chrono::milliseconds(1);; delay *= 2) {
192 bool success = false;
194 auto thr = DSched::thread(
195 [&] { success = FutexResult::AWOKEN == f.futexWait(0); });
196 /* sleep override */ std::this_thread::sleep_for(delay);
200 LOG(INFO) << "delay=" << delay.count() << "_ms, success=" << success;
207 TEST(Futex, clock_source) {
208 run_system_clock_test();
210 /* On some systems steady_clock is just an alias for system_clock. So,
211 * we must skip run_steady_clock_test if the two clocks are the same. */
212 if (!std::is_same<system_clock,steady_clock>::value) {
213 run_steady_clock_test();
217 TEST(Futex, basic_live) {
218 run_basic_tests<std::atomic>();
219 run_wait_until_tests<std::atomic>();
222 TEST(Futex, basic_emulated) {
223 run_basic_tests<EmulatedFutexAtomic>();
224 run_wait_until_tests<EmulatedFutexAtomic>();
227 TEST(Futex, basic_deterministic) {
228 DSched sched(DSched::uniform(0));
229 run_basic_tests<DeterministicAtomic>();
230 run_wait_until_tests<DeterministicAtomic>();
233 TEST(Futex, wake_blocked_live) {
234 run_wake_blocked_test<std::atomic>();
237 TEST(Futex, wake_blocked_emulated) {
238 run_wake_blocked_test<EmulatedFutexAtomic>();