2 * Copyright 2016 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.
25 #include <folly/detail/Futex.h>
26 #include <folly/detail/MemoryIdler.h>
27 #include <folly/portability/Asm.h>
31 /// A Baton allows a thread to block once and be awoken: it captures
32 /// a single handoff. During its lifecycle (from construction/reset to
33 /// destruction/reset) a baton must either be post()ed and wait()ed exactly
34 /// once each, or not at all.
36 /// Baton includes no internal padding, and is only 4 bytes in size.
37 /// Any alignment or padding to avoid false sharing is up to the user.
39 /// This is basically a stripped-down semaphore that supports only a
40 /// single call to sem_post and a single call to sem_wait. The current
41 /// posix semaphore sem_t isn't too bad, but this provides more a bit more
42 /// speed, inlining, smaller size, a guarantee that the implementation
43 /// won't change, and compatibility with DeterministicSchedule. By having
44 /// a much more restrictive lifecycle we can also add a bunch of assertions
45 /// that can help to catch race conditions ahead of time.
46 template <template<typename> class Atom = std::atomic>
48 constexpr Baton() : state_(INIT) {}
50 Baton(Baton const&) = delete;
51 Baton& operator=(Baton const&) = delete;
53 /// It is an error to destroy a Baton on which a thread is currently
54 /// wait()ing. In practice this means that the waiter usually takes
55 /// responsibility for destroying the Baton.
57 // The docblock for this function says that it can't be called when
58 // there is a concurrent waiter. We assume a strong version of this
59 // requirement in which the caller must _know_ that this is true, they
60 // are not allowed to be merely lucky. If two threads are involved,
61 // the destroying thread must actually have synchronized with the
62 // waiting thread after wait() returned. To convey causality the the
63 // waiting thread must have used release semantics and the destroying
64 // thread must have used acquire semantics for that communication,
65 // so we are guaranteed to see the post-wait() value of state_,
66 // which cannot be WAITING.
68 // Note that since we only care about a single memory location,
69 // the only two plausible memory orders here are relaxed and seq_cst.
70 assert(state_.load(std::memory_order_relaxed) != WAITING);
73 /// Equivalent to destroying the Baton and creating a new one. It is
74 /// a bug to call this while there is a waiting thread, so in practice
75 /// the waiter will be the one that resets the baton.
77 // See ~Baton for a discussion about why relaxed is okay here
78 assert(state_.load(std::memory_order_relaxed) != WAITING);
80 // We use a similar argument to justify the use of a relaxed store
81 // here. Since both wait() and post() are required to be called
82 // only once per lifetime, no thread can actually call those methods
83 // correctly after a reset() unless it synchronizes with the thread
84 // that performed the reset(). If a post() or wait() on another thread
85 // didn't synchronize, then regardless of what operation we performed
86 // here there would be a race on proper use of the Baton's spec
87 // (although not on any particular load and store). Put another way,
88 // we don't need to synchronize here because anybody that might rely
89 // on such synchronization is required by the baton rules to perform
90 // an additional synchronization that has the desired effect anyway.
92 // There is actually a similar argument to be made about the
93 // constructor, in which the fenceless constructor initialization
94 // of state_ is piggybacked on whatever synchronization mechanism
95 // distributes knowledge of the Baton's existence
96 state_.store(INIT, std::memory_order_relaxed);
99 /// Causes wait() to wake up. For each lifetime of a Baton (where a
100 /// lifetime starts at construction or reset() and ends at destruction
101 /// or reset()) there can be at most one call to post(). Any thread
104 /// Although we could implement a more generic semaphore semantics
105 /// without any extra size or CPU overhead, the single-call limitation
106 /// allows us to have better assert-ions during debug builds.
108 uint32_t before = state_.load(std::memory_order_acquire);
110 assert(before == INIT || before == WAITING || before == TIMED_OUT);
112 if (before == INIT &&
113 state_.compare_exchange_strong(before, EARLY_DELIVERY)) {
117 assert(before == WAITING || before == TIMED_OUT);
119 if (before == TIMED_OUT) {
123 assert(before == WAITING);
124 state_.store(LATE_DELIVERY, std::memory_order_release);
128 /// Waits until post() has been called in the current Baton lifetime.
129 /// May be called at most once during a Baton lifetime (construction
130 /// |reset until destruction|reset). If post is called before wait in
131 /// the current lifetime then this method returns immediately.
133 /// The restriction that there can be at most one wait() per lifetime
134 /// could be relaxed somewhat without any perf or size regressions,
135 /// but by making this condition very restrictive we can provide better
136 /// checking in debug builds.
138 if (spinWaitForEarlyDelivery()) {
139 assert(state_.load(std::memory_order_acquire) == EARLY_DELIVERY);
143 // guess we have to block :(
144 uint32_t expected = INIT;
145 if (!state_.compare_exchange_strong(expected, WAITING)) {
146 // CAS failed, last minute reprieve
147 assert(expected == EARLY_DELIVERY);
152 detail::MemoryIdler::futexWait(state_, WAITING);
154 // state_ is the truth even if FUTEX_WAIT reported a matching
155 // FUTEX_WAKE, since we aren't using type-stable storage and we
156 // don't guarantee reuse. The scenario goes like this: thread
157 // A's last touch of a Baton is a call to wake(), which stores
158 // LATE_DELIVERY and gets an unlucky context switch before delivering
159 // the corresponding futexWake. Thread B sees LATE_DELIVERY
160 // without consuming a futex event, because it calls futexWait
161 // with an expected value of WAITING and hence doesn't go to sleep.
162 // B returns, so the Baton's memory is reused and becomes another
163 // Baton (or a reuse of this one). B calls futexWait on the new
164 // Baton lifetime, then A wakes up and delivers a spurious futexWake
165 // to the same memory location. B's futexWait will then report a
166 // consumed wake event even though state_ is still WAITING.
168 // It would be possible to add an extra state_ dance to communicate
169 // that the futexWake has been sent so that we can be sure to consume
170 // it before returning, but that would be a perf and complexity hit.
171 uint32_t s = state_.load(std::memory_order_acquire);
172 assert(s == WAITING || s == LATE_DELIVERY);
174 if (s == LATE_DELIVERY) {
181 /// Similar to wait, but with a timeout. The thread is unblocked if the
183 /// Note: Only a single call to timed_wait/wait is allowed during a baton's
184 /// life-cycle (from construction/reset to destruction/reset). In other
185 /// words, after timed_wait the caller can't invoke wait/timed_wait/try_wait
186 /// again on the same baton without resetting it.
188 /// @param deadline Time until which the thread can block
189 /// @return true if the baton was posted to before timeout,
191 template <typename Clock, typename Duration = typename Clock::duration>
192 bool timed_wait(const std::chrono::time_point<Clock,Duration>& deadline) {
193 if (spinWaitForEarlyDelivery()) {
194 assert(state_.load(std::memory_order_acquire) == EARLY_DELIVERY);
198 // guess we have to block :(
199 uint32_t expected = INIT;
200 if (!state_.compare_exchange_strong(expected, WAITING)) {
201 // CAS failed, last minute reprieve
202 assert(expected == EARLY_DELIVERY);
207 auto rv = state_.futexWaitUntil(WAITING, deadline);
208 if (rv == folly::detail::FutexResult::TIMEDOUT) {
209 state_.store(TIMED_OUT, std::memory_order_release);
213 uint32_t s = state_.load(std::memory_order_acquire);
214 assert(s == WAITING || s == LATE_DELIVERY);
215 if (s == LATE_DELIVERY) {
221 /// Similar to timed_wait, but with a duration.
222 template <typename Clock = std::chrono::steady_clock, typename Duration>
223 bool timed_wait(const Duration& duration) {
224 auto deadline = Clock::now() + duration;
225 return timed_wait(deadline);
228 /// Similar to wait, but doesn't block the thread if it hasn't been posted.
230 /// try_wait has the following semantics:
231 /// - It is ok to call try_wait any number times on the same baton until
232 /// try_wait reports that the baton has been posted.
233 /// - It is ok to call timed_wait or wait on the same baton if try_wait
234 /// reports that baton hasn't been posted.
235 /// - If try_wait indicates that the baton has been posted, it is invalid to
236 /// call wait, try_wait or timed_wait on the same baton without resetting
238 /// @return true if baton has been posted, false othewise
240 auto s = state_.load(std::memory_order_acquire);
241 assert(s == INIT || s == EARLY_DELIVERY);
242 return s == EARLY_DELIVERY;
246 enum State : uint32_t {
255 // Must be positive. If multiple threads are actively using a
256 // higher-level data structure that uses batons internally, it is
257 // likely that the post() and wait() calls happen almost at the same
258 // time. In this state, we lose big 50% of the time if the wait goes
259 // to sleep immediately. On circa-2013 devbox hardware it costs about
260 // 7 usec to FUTEX_WAIT and then be awoken (half the t/iter as the
261 // posix_sem_pingpong test in BatonTests). We can improve our chances
262 // of EARLY_DELIVERY by spinning for a bit, although we have to balance
263 // this against the loss if we end up sleeping any way. Spins on this
264 // hw take about 7 nanos (all but 0.5 nanos is the pause instruction).
265 // We give ourself 300 spins, which is about 2 usec of waiting. As a
266 // partial consolation, since we are using the pause instruction we
267 // are giving a speed boost to the colocated hyperthread.
268 PreBlockAttempts = 300,
271 // Spin for "some time" (see discussion on PreBlockAttempts) waiting
274 // @return true if we received an early delivery during the wait,
275 // false otherwise. If the function returns true then
276 // state_ is guaranteed to be EARLY_DELIVERY
277 bool spinWaitForEarlyDelivery() {
279 static_assert(PreBlockAttempts > 0,
280 "isn't this assert clearer than an uninitialized variable warning?");
281 for (int i = 0; i < PreBlockAttempts; ++i) {
286 // The pause instruction is the polite way to spin, but it doesn't
287 // actually affect correctness to omit it if we don't have it.
288 // Pausing donates the full capabilities of the current core to
289 // its other hyperthreads for a dozen cycles or so
290 asm_volatile_pause();
296 detail::Futex<Atom> state_;