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/SmallLocks.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.
78 /// This must be heap-constructed. There's probably a way to enforce that in
79 /// code but since this is just internal detail code and I don't know how
80 /// off-hand, I'm punting.
83 assert(attached_ == 0);
87 Core(Core const&) = delete;
88 Core& operator=(Core const&) = delete;
90 // not movable (see comment in the implementation of Future::then)
91 Core(Core&&) noexcept = delete;
92 Core& operator=(Core&&) = delete;
94 /// May call from any thread
95 bool hasResult() const {
96 switch (fsm_.getState()) {
97 case State::OnlyResult:
108 /// May call from any thread
113 /// May call from any thread
118 throw FutureNotReady();
122 template <typename F>
123 class LambdaBufHelper {
125 explicit LambdaBufHelper(F&& func) : func_(std::forward<F>(func)) {}
126 void operator()(Try<T>&& t) {
127 SCOPE_EXIT { this->~LambdaBufHelper(); };
134 /// Call only from Future thread.
135 template <typename F>
136 void setCallback(F func) {
137 bool transitionToArmed = false;
138 auto setCallback_ = [&]{
139 context_ = RequestContext::saveContext();
141 // Move the lambda into the Core if it fits
142 if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
143 auto funcLoc = static_cast<LambdaBufHelper<F>*>((void*)lambdaBuf_);
144 new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
145 callback_ = std::ref(*funcLoc);
147 callback_ = std::move(func);
153 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
156 case State::OnlyResult:
157 FSM_UPDATE(fsm_, State::Armed, setCallback_);
158 transitionToArmed = true;
161 case State::OnlyCallback:
164 throw std::logic_error("setCallback called twice");
167 // we could always call this, it is an optimization to only call it when
168 // it might be needed.
169 if (transitionToArmed) {
174 /// Call only from Promise thread
175 void setResult(Try<T>&& t) {
176 bool transitionToArmed = false;
177 auto setResult_ = [&]{ result_ = std::move(t); };
180 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
183 case State::OnlyCallback:
184 FSM_UPDATE(fsm_, State::Armed, setResult_);
185 transitionToArmed = true;
188 case State::OnlyResult:
191 throw std::logic_error("setResult called twice");
194 if (transitionToArmed) {
199 /// Called by a destructing Future (in the Future thread, by definition)
200 void detachFuture() {
205 /// Called by a destructing Promise (in the Promise thread, by definition)
206 void detachPromise() {
207 // detachPromise() and setResult() should never be called in parallel
208 // so we don't need to protect this.
210 setResult(Try<T>(exception_wrapper(BrokenPromise())));
215 /// May call from any thread
220 /// May call from any thread
226 /// May call from any thread
227 bool isActive() { return active_; }
229 /// Call only from Future thread
230 void setExecutor(Executor* x, int8_t priority) {
231 folly::MSLGuard g(executorLock_);
233 priority_ = priority;
236 Executor* getExecutor() {
237 folly::MSLGuard g(executorLock_);
241 /// Call only from Future thread
242 void raise(exception_wrapper e) {
243 folly::MSLGuard guard(interruptLock_);
244 if (!interrupt_ && !hasResult()) {
245 interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
246 if (interruptHandler_) {
247 interruptHandler_(*interrupt_);
252 std::function<void(exception_wrapper const&)> getInterruptHandler() {
253 folly::MSLGuard guard(interruptLock_);
254 return interruptHandler_;
257 /// Call only from Promise thread
258 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
259 folly::MSLGuard guard(interruptLock_);
264 interruptHandler_ = std::move(fn);
270 void maybeCallback() {
274 FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
284 RequestContext::setContext(context_);
286 // TODO(6115514) semantic race on reading executor_ and setExecutor()
290 folly::MSLGuard g(executorLock_);
292 priority = priority_;
296 ++attached_; // keep Core alive until executor did its thing
298 if (LIKELY(x->getNumPriorities() == 1)) {
299 x->add([this]() mutable {
300 SCOPE_EXIT { detachOne(); };
301 callback_(std::move(*result_));
304 x->addWithPriority([this]() mutable {
305 SCOPE_EXIT { detachOne(); };
306 callback_(std::move(*result_));
310 result_ = Try<T>(exception_wrapper(std::current_exception()));
311 callback_(std::move(*result_));
314 callback_(std::move(*result_));
319 auto a = --attached_;
327 FSM<State> fsm_ {State::Start};
328 std::atomic<unsigned char> attached_ {2};
329 std::atomic<bool> active_ {true};
330 folly::MicroSpinLock interruptLock_ {0};
331 folly::MicroSpinLock executorLock_ {0};
332 int8_t priority_ {-1};
333 Executor* executor_ {nullptr};
334 folly::Optional<Try<T>> result_ {};
335 std::function<void(Try<T>&&)> callback_ {nullptr};
336 static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
337 char lambdaBuf_[lambdaBufSize];
338 std::shared_ptr<RequestContext> context_ {nullptr};
339 std::unique_ptr<exception_wrapper> interrupt_ {};
340 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
343 template <typename... Ts>
344 struct VariadicContext {
347 p.setValue(std::move(results));
349 Promise<std::tuple<Try<Ts>... >> p;
350 std::tuple<Try<Ts>... > results;
351 typedef Future<std::tuple<Try<Ts>...>> type;
354 template <typename... Ts, typename THead, typename... Fs>
355 typename std::enable_if<sizeof...(Fs) == 0, void>::type
356 collectAllVariadicHelper(std::shared_ptr<VariadicContext<Ts...>> ctx,
357 THead&& head, Fs&&... tail) {
358 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
359 std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
363 template <typename... Ts, typename THead, typename... Fs>
364 typename std::enable_if<sizeof...(Fs) != 0, void>::type
365 collectAllVariadicHelper(std::shared_ptr<VariadicContext<Ts...>> ctx,
366 THead&& head, Fs&&... tail) {
367 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
368 std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
370 // template tail-recursion
371 collectAllVariadicHelper(ctx, std::forward<Fs>(tail)...);