2 * Copyright 2014 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.
23 #include <type_traits>
26 #include <folly/MoveWrapper.h>
27 #include <folly/wangle/Promise.h>
28 #include <folly/wangle/Try.h>
30 namespace folly { namespace wangle {
33 template <class> struct Core;
34 template <class...> struct VariadicContext;
38 typedef typename std::conditional<
39 std::is_same<T, void>::value,
45 template <class> struct Promise;
47 template <typename T> struct isFuture;
55 Future(Future const&) = delete;
56 Future& operator=(Future const&) = delete;
59 Future(Future&&) noexcept;
60 Future& operator=(Future&&);
64 /** Return the reference to result. Should not be called if !isReady().
65 Will rethrow the exception if an exception has been
68 This function is not thread safe - the returned Future can only
69 be executed from the thread that the executor runs it in.
70 See below for a thread safe version
72 typename std::add_lvalue_reference<T>::type
74 typename std::add_lvalue_reference<const T>::type
77 /// Returns an inactive Future which will call back on the other side of
78 /// executor (when it is activated).
80 /// NB remember that Futures activate when they destruct. This is good,
81 /// it means that this will work:
83 /// f.via(e).then(a).then(b);
85 /// a and b will execute in the same context (the far side of e), because
86 /// the Future (temporary variable) created by via(e) does not call back
87 /// until it destructs, which is after then(a) and then(b) have been wired
90 /// But this is still racy:
92 /// f = f.via(e).then(a);
94 // The ref-qualifier allows for `this` to be moved out so we
95 // don't get access-after-free situations in chaining.
96 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
97 template <typename Executor>
98 Future<T> via(Executor* executor) &&;
100 /// This variant creates a new future, where the ref-qualifier && version
101 /// moves `this` out. This one is less efficient but avoids confusing users
102 /// when "return f.via(x);" fails.
103 template <typename Executor>
104 Future<T> via(Executor* executor) &;
106 /** True when the result (or exception) is ready. */
107 bool isReady() const;
109 /** A reference to the Try of the value */
112 /** When this Future has completed, execute func which is a function that
113 takes a Try<T>&&. A Future for the return type of func is
116 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
118 The Future given to the functor is ready, and the functor may call
119 value(), which may rethrow if this has captured an exception. If func
120 throws, the exception will be captured in the Future that is returned.
122 /* TODO n3428 and other async frameworks have something like then(scheduler,
123 Future), we might want to support a similar API which could be
124 implemented a little more efficiently than
125 f.via(executor).then(callback) */
127 typename std::enable_if<
128 !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
129 Future<typename std::result_of<F(Try<T>&&)>::type> >::type
132 /// Variant where func takes a T directly, bypassing a try. Any exceptions
133 /// will be implicitly passed on to the resultant Future.
135 /// Future<int> f = makeFuture<int>(42).then([](int i) { return i+1; });
137 typename std::enable_if<
138 !std::is_same<T, void>::value &&
139 !isFuture<typename std::result_of<
140 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
141 Future<typename std::result_of<
142 F(typename detail::AliasIfVoid<T>::type&&)>::type> >::type
145 /// Like the above variant, but for void futures. That is, func takes no
148 /// Future<int> f = makeFuture().then([] { return 42; });
150 typename std::enable_if<
151 std::is_same<T, void>::value &&
152 !isFuture<typename std::result_of<F()>::type>::value,
153 Future<typename std::result_of<F()>::type> >::type
156 /// Variant where func returns a Future<T> instead of a T. e.g.
158 /// Future<string> f2 = f1.then(
159 /// [](Try<T>&&) { return makeFuture<string>("foo"); });
161 typename std::enable_if<
162 isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
163 Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
166 /// Variant where func returns a Future<T2> and takes a T directly, bypassing
167 /// a Try. Any exceptions will be implicitly passed on to the resultant
168 /// Future. For example,
170 /// Future<int> f = makeFuture<int>(42).then(
171 /// [](int i) { return makeFuture<int>(i+1); });
173 typename std::enable_if<
174 !std::is_same<T, void>::value &&
175 isFuture<typename std::result_of<
176 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
177 Future<typename std::result_of<
178 F(typename detail::AliasIfVoid<T>::type&&)>::type::value_type> >::type
181 /// Like the above variant, but for void futures. That is, func takes no
182 /// argument and returns a future.
184 /// Future<int> f = makeFuture().then(
185 /// [] { return makeFuture<int>(42); });
187 typename std::enable_if<
188 std::is_same<T, void>::value &&
189 isFuture<typename std::result_of<F()>::type>::value,
190 Future<typename std::result_of<F()>::type::value_type> >::type
193 /// Variant where func is an ordinary function (static method, method)
195 /// R doWork(Try<T>&&);
197 /// Future<R> f2 = f1.then(doWork);
202 /// static R doWork(Try<T>&&); }
204 /// Future<R> f2 = f1.then(&Worker::doWork);
205 template <class = T, class R = std::nullptr_t>
206 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
207 inline then(R(*func)(Try<T>&&)) {
208 return then([func](Try<T>&& t) {
209 return (*func)(std::move(t));
213 /// Variant where func returns a Future<R> instead of a R. e.g.
216 /// Future<R> doWork(Try<T>&&); }
218 /// Future<R> f2 = f1.then(&Worker::doWork);
219 template <class = T, class R = std::nullptr_t>
220 typename std::enable_if<isFuture<R>::value, R>::type
221 inline then(R(*func)(Try<T>&&)) {
222 return then([func](Try<T>&& t) {
223 return (*func)(std::move(t));
227 /// Variant where func is an member function
230 /// R doWork(Try<T>&&); }
233 /// Future<R> f2 = f1.then(w, &Worker::doWork);
234 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
235 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
236 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
237 return then([instance, func](Try<T>&& t) {
238 return (instance->*func)(std::move(t));
242 // Same as above, but func takes void instead of Try<void>&&
243 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
244 typename std::enable_if<
245 std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
246 inline then(Caller *instance, R(Caller::*func)()) {
247 return then([instance, func]() {
248 return (instance->*func)();
252 // Same as above, but func takes T&& instead of Try<T>&&
253 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
254 typename std::enable_if<
255 !std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
258 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
259 return then([instance, func](T&& t) {
260 return (instance->*func)(std::move(t));
264 /// Variant where func returns a Future<R> instead of a R. e.g.
267 /// Future<R> doWork(Try<T>&&); }
270 /// Future<R> f2 = f1.then(w, &Worker::doWork);
271 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
272 typename std::enable_if<isFuture<R>::value, R>::type
273 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
274 return then([instance, func](Try<T>&& t) {
275 return (instance->*func)(std::move(t));
279 // Same as above, but func takes void instead of Try<void>&&
280 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
281 typename std::enable_if<
282 std::is_same<T, void>::value && isFuture<R>::value, R>::type
283 inline then(Caller *instance, R(Caller::*func)()) {
284 return then([instance, func]() {
285 return (instance->*func)();
289 // Same as above, but func takes T&& instead of Try<T>&&
290 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
291 typename std::enable_if<
292 !std::is_same<T, void>::value && isFuture<R>::value, R>::type
295 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
296 return then([instance, func](T&& t) {
297 return (instance->*func)(std::move(t));
301 /// Convenience method for ignoring the value and creating a Future<void>.
302 /// Exceptions still propagate.
305 /// This is not the method you're looking for.
307 /// This needs to be public because it's used by make* and when*, and it's
308 /// not worth listing all those and their fancy template signatures as
309 /// friends. But it's not for public consumption.
311 void setCallback_(F&& func);
313 /// A Future's callback is executed when all three of these conditions have
314 /// become true: it has a value (set by the Promise), it has a callback (set
315 /// by then), and it is active (active by default).
317 /// Inactive Futures will activate upon destruction.
318 Future<T>& activate() & {
322 Future<T>& deactivate() & {
326 Future<T> activate() && {
328 return std::move(*this);
330 Future<T> deactivate() && {
332 return std::move(*this);
336 return core_->isActive();
340 void raise(E&& exception) {
341 raise(std::make_exception_ptr(std::forward<E>(exception)));
344 /// Raise an interrupt. If the promise holder has an interrupt
345 /// handler it will be called and potentially stop asynchronous work from
346 /// being done. This is advisory only - a promise holder may not set an
347 /// interrupt handler, or may do anything including ignore. But, if you know
348 /// your future supports this the most likely result is stopping or
349 /// preventing the asynchronous operation (if in time), and the promise
350 /// holder setting an exception on the future. (That may happen
351 /// asynchronously, of course.)
352 void raise(std::exception_ptr interrupt);
355 raise(FutureCancellation());
359 typedef detail::Core<T>* corePtr;
361 // shared core state object
365 Future(corePtr obj) : core_(obj) {}
369 void throwIfInvalid() const;
371 friend class Promise<T>;
375 Make a completed Future by moving in a value. e.g.
378 auto f = makeFuture(std::move(foo));
382 auto f = makeFuture<string>("foo");
385 Future<typename std::decay<T>::type> makeFuture(T&& t);
387 /** Make a completed void Future. */
388 Future<void> makeFuture();
390 /** Make a completed Future by executing a function. If the function throws
391 we capture the exception, otherwise we capture the result. */
395 typename std::enable_if<
396 !std::is_reference<F>::value, bool>::type sdf = false)
397 -> Future<decltype(func())>;
402 -> Future<decltype(func())>;
404 /// Make a failed Future from an exception_ptr.
405 /// Because the Future's type cannot be inferred you have to specify it, e.g.
407 /// auto f = makeFuture<string>(std::current_exception());
409 Future<T> makeFuture(std::exception_ptr const& e);
411 /** Make a Future from an exception type E that can be passed to
412 std::make_exception_ptr(). */
413 template <class T, class E>
414 typename std::enable_if<std::is_base_of<std::exception, E>::value,
416 makeFuture(E const& e);
418 /** Make a Future out of a Try */
420 Future<T> makeFuture(Try<T>&& t);
423 * Return a new Future that will call back on the given Executor.
424 * This is just syntactic sugar for makeFuture().via(executor)
426 * @param executor the Executor to call back on
428 * @returns a void Future that will call back on the given executor
430 template <typename Executor>
431 Future<void> via(Executor* executor);
433 /** When all the input Futures complete, the returned Future will complete.
434 Errors do not cause early termination; this Future will always succeed
435 after all its Futures have finished (whether successfully or with an
438 The Futures are moved in, so your copies are invalid. If you need to
439 chain further from these Futures, use the variant with an output iterator.
441 XXX is this still true?
442 This function is thread-safe for Futures running on different threads.
444 The return type for Future<T> input is a Future<std::vector<Try<T>>>
446 template <class InputIterator>
447 Future<std::vector<Try<
448 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
449 whenAll(InputIterator first, InputIterator last);
451 /// This version takes a varying number of Futures instead of an iterator.
452 /// The return type for (Future<T1>, Future<T2>, ...) input
453 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
454 /// The Futures are moved in, so your copies are invalid.
455 template <typename... Fs>
456 typename detail::VariadicContext<
457 typename std::decay<Fs>::type::value_type...>::type
460 /** The result is a pair of the index of the first Future to complete and
461 the Try. If multiple Futures complete at the same time (or are already
462 complete when passed in), the "winner" is chosen non-deterministically.
464 This function is thread-safe for Futures running on different threads.
466 template <class InputIterator>
469 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
470 whenAny(InputIterator first, InputIterator last);
472 /** when n Futures have completed, the Future completes with a vector of
473 the index and Try of those n Futures (the indices refer to the original
474 order, but the result vector will be in an arbitrary order)
478 template <class InputIterator>
479 Future<std::vector<std::pair<
481 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
482 whenN(InputIterator first, InputIterator last, size_t n);
484 /** Wait for the given future to complete on a semaphore. Returns a completed
485 * future containing the result.
487 * NB if the promise for the future would be fulfilled in the same thread that
488 * you call this, it will deadlock.
491 Future<T> waitWithSemaphore(Future<T>&& f);
493 /** Wait for up to `timeout` for the given future to complete. Returns a future
494 * which may or may not be completed depending whether the given future
497 * Note: each call to this starts a (short-lived) thread and allocates memory.
499 template <typename T, class Duration>
500 Future<T> waitWithSemaphore(Future<T>&& f, Duration timeout);
504 #include <folly/wangle/Future-inl.h>