2 * Copyright 2015 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.
24 #include <folly/Optional.h>
25 #include <folly/MicroSpinLock.h>
27 #include <folly/futures/Try.h>
28 #include <folly/futures/Promise.h>
29 #include <folly/futures/Future.h>
30 #include <folly/Executor.h>
31 #include <folly/futures/detail/FSM.h>
33 #include <folly/io/async/Request.h>
35 namespace folly { namespace detail {
44 This state machine is fairly self-explanatory. The most important bit is
45 that the callback is only executed on the transition from Armed to Done,
46 and that transition can happen immediately after transitioning from Only*
47 to Armed, if it is active (the usual case).
49 enum class State : uint8_t {
57 /// The shared state object for Future and Promise.
58 /// Some methods must only be called by either the Future thread or the
59 /// Promise thread. The Future thread is the thread that currently "owns" the
60 /// Future and its callback-related operations, and the Promise thread is
61 /// likewise the thread that currently "owns" the Promise and its
62 /// result-related operations. Also, Futures own interruption, Promises own
63 /// interrupt handlers. Unfortunately, there are things that users can do to
64 /// break this, and we can't detect that. However if they follow move
65 /// semantics religiously wrt threading, they should be ok.
67 /// It's worth pointing out that Futures and/or Promises can and usually will
68 /// migrate between threads, though this usually happens within the API code.
69 /// For example, an async operation will probably make a Promise, grab its
70 /// Future, then move the Promise into another thread that will eventually
71 /// fulfill it. With executors and via, this gets slightly more complicated at
72 /// first blush, but it's the same principle. In general, as long as the user
73 /// doesn't access a Future or Promise object from more than one thread at a
74 /// time there won't be any problems.
77 static_assert(!std::is_void<T>::value,
78 "void futures are not supported. Use Unit instead.");
80 /// This must be heap-constructed. There's probably a way to enforce that in
81 /// code but since this is just internal detail code and I don't know how
82 /// off-hand, I'm punting.
83 Core() : result_(), fsm_(State::Start), attached_(2) {}
85 explicit Core(Try<T>&& t)
86 : result_(std::move(t)),
87 fsm_(State::OnlyResult),
91 DCHECK(attached_ == 0);
95 Core(Core const&) = delete;
96 Core& operator=(Core const&) = delete;
98 // not movable (see comment in the implementation of Future::then)
99 Core(Core&&) noexcept = delete;
100 Core& operator=(Core&&) = delete;
102 /// May call from any thread
103 bool hasResult() const {
104 switch (fsm_.getState()) {
105 case State::OnlyResult:
116 /// May call from any thread
121 /// May call from any thread
126 throw FutureNotReady();
130 template <typename F>
131 class LambdaBufHelper {
133 template <typename FF>
134 explicit LambdaBufHelper(FF&& func) : func_(std::forward<FF>(func)) {}
135 void operator()(Try<T>&& t) {
136 SCOPE_EXIT { this->~LambdaBufHelper(); };
143 /// Call only from Future thread.
144 template <typename F>
145 void setCallback(F func) {
146 bool transitionToArmed = false;
147 auto setCallback_ = [&]{
148 context_ = RequestContext::saveContext();
150 // Move the lambda into the Core if it fits
151 if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
152 auto funcLoc = reinterpret_cast<LambdaBufHelper<F>*>(&lambdaBuf_);
153 new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
154 callback_ = std::ref(*funcLoc);
156 callback_ = std::move(func);
162 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
165 case State::OnlyResult:
166 FSM_UPDATE(fsm_, State::Armed, setCallback_);
167 transitionToArmed = true;
170 case State::OnlyCallback:
173 throw std::logic_error("setCallback called twice");
176 // we could always call this, it is an optimization to only call it when
177 // it might be needed.
178 if (transitionToArmed) {
183 /// Call only from Promise thread
184 void setResult(Try<T>&& t) {
185 bool transitionToArmed = false;
186 auto setResult_ = [&]{ result_ = std::move(t); };
189 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
192 case State::OnlyCallback:
193 FSM_UPDATE(fsm_, State::Armed, setResult_);
194 transitionToArmed = true;
197 case State::OnlyResult:
200 throw std::logic_error("setResult called twice");
203 if (transitionToArmed) {
208 /// Called by a destructing Future (in the Future thread, by definition)
209 void detachFuture() {
214 /// Called by a destructing Promise (in the Promise thread, by definition)
215 void detachPromise() {
216 // detachPromise() and setResult() should never be called in parallel
217 // so we don't need to protect this.
218 if (UNLIKELY(!result_)) {
219 setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
224 /// May call from any thread
226 active_.store(false, std::memory_order_release);
229 /// May call from any thread
231 active_.store(true, std::memory_order_release);
235 /// May call from any thread
236 bool isActive() { return active_.load(std::memory_order_acquire); }
238 /// Call only from Future thread
239 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
240 if (!executorLock_.try_lock()) {
241 executorLock_.lock();
244 priority_ = priority;
245 executorLock_.unlock();
248 void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
250 priority_ = priority;
253 Executor* getExecutor() {
257 /// Call only from Future thread
258 void raise(exception_wrapper e) {
259 if (!interruptLock_.try_lock()) {
260 interruptLock_.lock();
262 if (!interrupt_ && !hasResult()) {
263 interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
264 if (interruptHandler_) {
265 interruptHandler_(*interrupt_);
268 interruptLock_.unlock();
271 std::function<void(exception_wrapper const&)> getInterruptHandler() {
272 if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
275 if (!interruptLock_.try_lock()) {
276 interruptLock_.lock();
278 auto handler = interruptHandler_;
279 interruptLock_.unlock();
283 /// Call only from Promise thread
284 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
285 if (!interruptLock_.try_lock()) {
286 interruptLock_.lock();
292 setInterruptHandlerNoLock(std::move(fn));
295 interruptLock_.unlock();
298 void setInterruptHandlerNoLock(
299 std::function<void(exception_wrapper const&)> fn) {
300 interruptHandlerSet_.store(true, std::memory_order_relaxed);
301 interruptHandler_ = std::move(fn);
305 void maybeCallback() {
308 if (active_.load(std::memory_order_acquire)) {
309 FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
319 Executor* x = executor_;
322 if (!executorLock_.try_lock()) {
323 executorLock_.lock();
326 priority = priority_;
327 executorLock_.unlock();
331 // keep Core alive until executor did its thing
334 if (LIKELY(x->getNumPriorities() == 1)) {
335 x->add([this]() mutable {
336 SCOPE_EXIT { detachOne(); };
337 RequestContext::setContext(context_);
338 SCOPE_EXIT { callback_ = {}; };
339 callback_(std::move(*result_));
342 x->addWithPriority([this]() mutable {
343 SCOPE_EXIT { detachOne(); };
344 RequestContext::setContext(context_);
345 SCOPE_EXIT { callback_ = {}; };
346 callback_(std::move(*result_));
350 --attached_; // Account for extra ++attached_ before try
351 RequestContext::setContext(context_);
352 result_ = Try<T>(exception_wrapper(std::current_exception()));
353 SCOPE_EXIT { callback_ = {}; };
354 callback_(std::move(*result_));
357 RequestContext::setContext(context_);
358 SCOPE_EXIT { callback_ = {}; };
359 callback_(std::move(*result_));
364 auto a = --attached_;
372 // lambdaBuf occupies exactly one cache line
373 static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
374 typename std::aligned_storage<lambdaBufSize>::type lambdaBuf_;
375 // place result_ next to increase the likelihood that the value will be
376 // contained entirely in one cache line
377 folly::Optional<Try<T>> result_;
378 std::function<void(Try<T>&&)> callback_ {nullptr};
380 std::atomic<unsigned char> attached_;
381 std::atomic<bool> active_ {true};
382 std::atomic<bool> interruptHandlerSet_ {false};
383 folly::MicroSpinLock interruptLock_ {0};
384 folly::MicroSpinLock executorLock_ {0};
385 int8_t priority_ {-1};
386 Executor* executor_ {nullptr};
387 std::shared_ptr<RequestContext> context_ {nullptr};
388 std::unique_ptr<exception_wrapper> interrupt_ {};
389 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
392 template <typename... Ts>
393 struct CollectAllVariadicContext {
394 CollectAllVariadicContext() {}
395 template <typename T, size_t I>
396 inline void setPartialResult(Try<T>& t) {
397 std::get<I>(results) = std::move(t);
399 ~CollectAllVariadicContext() {
400 p.setValue(std::move(results));
402 Promise<std::tuple<Try<Ts>...>> p;
403 std::tuple<Try<Ts>...> results;
404 typedef Future<std::tuple<Try<Ts>...>> type;
407 template <typename... Ts>
408 struct CollectVariadicContext {
409 CollectVariadicContext() {}
410 template <typename T, size_t I>
411 inline void setPartialResult(Try<T>& t) {
412 if (t.hasException()) {
413 if (!threw.exchange(true)) {
414 p.setException(std::move(t.exception()));
417 std::get<I>(results) = std::move(t);
420 ~CollectVariadicContext() {
421 if (!threw.exchange(true)) {
422 p.setValue(unwrap(std::move(results)));
425 Promise<std::tuple<Ts...>> p;
426 std::tuple<folly::Try<Ts>...> results;
427 std::atomic<bool> threw {false};
428 typedef Future<std::tuple<Ts...>> type;
431 template <typename... Ts2>
432 static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& o,
434 static_assert(sizeof...(ts2) <
435 std::tuple_size<std::tuple<folly::Try<Ts>...>>::value,
436 "Non-templated unwrap should be used instead");
437 assert(std::get<sizeof...(ts2)>(o).hasValue());
439 return unwrap(std::move(o),
440 std::forward<Ts2>(ts2)...,
441 std::move(*std::get<sizeof...(ts2)>(o)));
444 static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& /* o */,
446 return std::tuple<Ts...>(std::forward<Ts>(ts)...);
450 template <template <typename...> class T, typename... Ts>
451 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
455 template <template <typename ...> class T, typename... Ts,
456 typename THead, typename... TTail>
457 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
458 THead&& head, TTail&&... tail) {
459 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
460 ctx->template setPartialResult<typename THead::value_type,
461 sizeof...(Ts) - sizeof...(TTail) - 1>(t);
463 // template tail-recursion
464 collectVariadicHelper(ctx, std::forward<TTail>(tail)...);