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.
25 #include <folly/Executor.h>
26 #include <folly/Function.h>
27 #include <folly/MicroSpinLock.h>
28 #include <folly/Optional.h>
29 #include <folly/ScopeGuard.h>
30 #include <folly/Try.h>
31 #include <folly/Utility.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/detail/FSM.h>
35 #include <folly/io/async/Request.h>
37 namespace folly { namespace detail {
46 This state machine is fairly self-explanatory. The most important bit is
47 that the callback is only executed on the transition from Armed to Done,
48 and that transition can happen immediately after transitioning from Only*
49 to Armed, if it is active (the usual case).
51 enum class State : uint8_t {
59 /// The shared state object for Future and Promise.
60 /// Some methods must only be called by either the Future thread or the
61 /// Promise thread. The Future thread is the thread that currently "owns" the
62 /// Future and its callback-related operations, and the Promise thread is
63 /// likewise the thread that currently "owns" the Promise and its
64 /// result-related operations. Also, Futures own interruption, Promises own
65 /// interrupt handlers. Unfortunately, there are things that users can do to
66 /// break this, and we can't detect that. However if they follow move
67 /// semantics religiously wrt threading, they should be ok.
69 /// It's worth pointing out that Futures and/or Promises can and usually will
70 /// migrate between threads, though this usually happens within the API code.
71 /// For example, an async operation will probably make a Promise, grab its
72 /// Future, then move the Promise into another thread that will eventually
73 /// fulfill it. With executors and via, this gets slightly more complicated at
74 /// first blush, but it's the same principle. In general, as long as the user
75 /// doesn't access a Future or Promise object from more than one thread at a
76 /// time there won't be any problems.
79 static_assert(!std::is_void<T>::value,
80 "void futures are not supported. Use Unit instead.");
82 /// This must be heap-constructed. There's probably a way to enforce that in
83 /// code but since this is just internal detail code and I don't know how
84 /// off-hand, I'm punting.
85 Core() : result_(), fsm_(State::Start), attached_(2) {}
87 explicit Core(Try<T>&& t)
88 : result_(std::move(t)),
89 fsm_(State::OnlyResult),
92 template <typename... Args>
93 explicit Core(in_place_t, Args&&... args) noexcept(
94 std::is_nothrow_constructible<T, Args&&...>::value)
95 : result_(in_place, in_place, std::forward<Args>(args)...),
96 fsm_(State::OnlyResult),
100 DCHECK(attached_ == 0);
104 Core(Core const&) = delete;
105 Core& operator=(Core const&) = delete;
107 // not movable (see comment in the implementation of Future::then)
108 Core(Core&&) noexcept = delete;
109 Core& operator=(Core&&) = delete;
111 /// May call from any thread
112 bool hasResult() const noexcept {
113 switch (fsm_.getState()) {
114 case State::OnlyResult:
125 /// May call from any thread
126 bool ready() const noexcept {
130 /// May call from any thread
135 throw FutureNotReady();
139 /// Call only from Future thread.
140 template <typename F>
141 void setCallback(F&& func) {
142 bool transitionToArmed = false;
143 auto setCallback_ = [&]{
144 context_ = RequestContext::saveContext();
145 callback_ = std::forward<F>(func);
150 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
153 case State::OnlyResult:
154 FSM_UPDATE(fsm_, State::Armed, setCallback_);
155 transitionToArmed = true;
158 case State::OnlyCallback:
161 throw std::logic_error("setCallback called twice");
164 // we could always call this, it is an optimization to only call it when
165 // it might be needed.
166 if (transitionToArmed) {
171 /// Call only from Promise thread
172 void setResult(Try<T>&& t) {
173 bool transitionToArmed = false;
174 auto setResult_ = [&]{ result_ = std::move(t); };
177 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
180 case State::OnlyCallback:
181 FSM_UPDATE(fsm_, State::Armed, setResult_);
182 transitionToArmed = true;
185 case State::OnlyResult:
188 throw std::logic_error("setResult called twice");
191 if (transitionToArmed) {
196 /// Called by a destructing Future (in the Future thread, by definition)
197 void detachFuture() {
202 /// Called by a destructing Promise (in the Promise thread, by definition)
203 void detachPromise() {
204 // detachPromise() and setResult() should never be called in parallel
205 // so we don't need to protect this.
206 if (UNLIKELY(!result_)) {
207 setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
212 /// May call from any thread
214 active_.store(false, std::memory_order_release);
217 /// May call from any thread
219 active_.store(true, std::memory_order_release);
223 /// May call from any thread
224 bool isActive() { return active_.load(std::memory_order_acquire); }
226 /// Call only from Future thread
227 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
228 if (!executorLock_.try_lock()) {
229 executorLock_.lock();
232 priority_ = priority;
233 executorLock_.unlock();
236 void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
238 priority_ = priority;
241 Executor* getExecutor() {
245 /// Call only from Future thread
246 void raise(exception_wrapper e) {
247 if (!interruptLock_.try_lock()) {
248 interruptLock_.lock();
250 if (!interrupt_ && !hasResult()) {
251 interrupt_ = std::make_unique<exception_wrapper>(std::move(e));
252 if (interruptHandler_) {
253 interruptHandler_(*interrupt_);
256 interruptLock_.unlock();
259 std::function<void(exception_wrapper const&)> getInterruptHandler() {
260 if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
263 if (!interruptLock_.try_lock()) {
264 interruptLock_.lock();
266 auto handler = interruptHandler_;
267 interruptLock_.unlock();
271 /// Call only from Promise thread
272 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
273 if (!interruptLock_.try_lock()) {
274 interruptLock_.lock();
280 setInterruptHandlerNoLock(std::move(fn));
283 interruptLock_.unlock();
286 void setInterruptHandlerNoLock(
287 std::function<void(exception_wrapper const&)> fn) {
288 interruptHandlerSet_.store(true, std::memory_order_relaxed);
289 interruptHandler_ = std::move(fn);
293 // Helper class that stores a pointer to the `Core` object and calls
294 // `derefCallback` and `detachOne` in the destructor.
295 class CoreAndCallbackReference {
297 explicit CoreAndCallbackReference(Core* core) noexcept : core_(core) {}
299 ~CoreAndCallbackReference() {
301 core_->derefCallback();
306 CoreAndCallbackReference(CoreAndCallbackReference const& o) = delete;
307 CoreAndCallbackReference& operator=(CoreAndCallbackReference const& o) =
310 CoreAndCallbackReference(CoreAndCallbackReference&& o) noexcept {
311 std::swap(core_, o.core_);
314 Core* getCore() const noexcept {
319 Core* core_{nullptr};
322 void maybeCallback() {
325 if (active_.load(std::memory_order_acquire)) {
326 FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
336 Executor* x = executor_;
337 // initialize, solely to appease clang's -Wconditional-uninitialized
340 if (!executorLock_.try_lock()) {
341 executorLock_.lock();
344 priority = priority_;
345 executorLock_.unlock();
349 exception_wrapper ew;
350 // We need to reset `callback_` after it was executed (which can happen
351 // through the executor or, if `Executor::add` throws, below). The
352 // executor might discard the function without executing it (now or
353 // later), in which case `callback_` also needs to be reset.
354 // The `Core` has to be kept alive throughout that time, too. Hence we
355 // increment `attached_` and `callbackReferences_` by two, and construct
356 // exactly two `CoreAndCallbackReference` objects, which call
357 // `derefCallback` and `detachOne` in their destructor. One will guard
358 // this scope, the other one will guard the lambda passed to the executor.
360 callbackReferences_ += 2;
361 CoreAndCallbackReference guard_local_scope(this);
362 CoreAndCallbackReference guard_lambda(this);
364 if (LIKELY(x->getNumPriorities() == 1)) {
365 x->add([core_ref = std::move(guard_lambda)]() mutable {
366 auto cr = std::move(core_ref);
367 Core* const core = cr.getCore();
368 RequestContextScopeGuard rctx(core->context_);
369 core->callback_(std::move(*core->result_));
373 [core_ref = std::move(guard_lambda)]() mutable {
374 auto cr = std::move(core_ref);
375 Core* const core = cr.getCore();
376 RequestContextScopeGuard rctx(core->context_);
377 core->callback_(std::move(*core->result_));
381 } catch (const std::exception& e) {
382 ew = exception_wrapper(std::current_exception(), e);
384 ew = exception_wrapper(std::current_exception());
387 RequestContextScopeGuard rctx(context_);
388 result_ = Try<T>(std::move(ew));
389 callback_(std::move(*result_));
397 RequestContextScopeGuard rctx(context_);
398 callback_(std::move(*result_));
403 auto a = attached_--;
410 void derefCallback() {
411 if (--callbackReferences_ == 0) {
416 folly::Function<void(Try<T>&&)> callback_;
417 // place result_ next to increase the likelihood that the value will be
418 // contained entirely in one cache line
419 folly::Optional<Try<T>> result_;
421 std::atomic<unsigned char> attached_;
422 std::atomic<unsigned char> callbackReferences_{0};
423 std::atomic<bool> active_ {true};
424 std::atomic<bool> interruptHandlerSet_ {false};
425 folly::MicroSpinLock interruptLock_ {0};
426 folly::MicroSpinLock executorLock_ {0};
427 int8_t priority_ {-1};
428 Executor* executor_ {nullptr};
429 std::shared_ptr<RequestContext> context_ {nullptr};
430 std::unique_ptr<exception_wrapper> interrupt_ {};
431 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
434 template <template <typename...> class T, typename... Ts>
435 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
439 template <template <typename ...> class T, typename... Ts,
440 typename THead, typename... TTail>
441 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
442 THead&& head, TTail&&... tail) {
443 using ValueType = typename std::decay<THead>::type::value_type;
444 std::forward<THead>(head).setCallback_([ctx](Try<ValueType>&& t) {
445 ctx->template setPartialResult<
447 sizeof...(Ts) - sizeof...(TTail)-1>(t);
449 // template tail-recursion
450 collectVariadicHelper(ctx, std::forward<TTail>(tail)...);