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;
36 template <class> struct Promise;
38 template <typename T> struct isFuture;
46 Future(Future const&) = delete;
47 Future& operator=(Future const&) = delete;
50 Future(Future&&) noexcept;
51 Future& operator=(Future&&);
55 /** Return the reference to result. Should not be called if !isReady().
56 Will rethrow the exception if an exception has been
59 This function is not thread safe - the returned Future can only
60 be executed from the thread that the executor runs it in.
61 See below for a thread safe version
63 typename std::add_lvalue_reference<T>::type
65 typename std::add_lvalue_reference<const T>::type
68 /// Returns an inactive Future which will call back on the other side of
69 /// executor (when it is activated).
71 /// NB remember that Futures activate when they destruct. This is good,
72 /// it means that this will work:
74 /// f.via(e).then(a).then(b);
76 /// a and b will execute in the same context (the far side of e), because
77 /// the Future (temporary variable) created by via(e) does not call back
78 /// until it destructs, which is after then(a) and then(b) have been wired
81 /// But this is still racy:
83 /// f = f.via(e).then(a);
86 /// If you need something like that, use a Later.
87 template <typename Executor>
88 Future<T> via(Executor* executor);
90 /** True when the result (or exception) is ready. */
93 /** A reference to the Try of the value */
96 /** When this Future has completed, execute func which is a function that
97 takes a Try<T>&&. A Future for the return type of func is
100 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
102 The Future given to the functor is ready, and the functor may call
103 value(), which may rethrow if this has captured an exception. If func
104 throws, the exception will be captured in the Future that is returned.
106 /* TODO n3428 and other async frameworks have something like then(scheduler,
107 Future), we might want to support a similar API which could be
108 implemented a little more efficiently than
109 f.via(executor).then(callback) */
111 typename std::enable_if<
112 !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
113 Future<typename std::result_of<F(Try<T>&&)>::type> >::type
116 /// Variant where func returns a Future<T> instead of a T. e.g.
118 /// Future<string> f2 = f1.then(
119 /// [](Try<T>&&) { return makeFuture<string>("foo"); });
121 typename std::enable_if<
122 isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
123 Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
126 /// Variant where func is an ordinary function (static method, method)
128 /// R doWork(Try<T>&&);
130 /// Future<R> f2 = f1.then(doWork);
135 /// static R doWork(Try<T>&&); }
137 /// Future<R> f2 = f1.then(&Worker::doWork);
138 template <class = T, class R = std::nullptr_t>
139 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
140 inline then(R(*func)(Try<T>&&)) {
141 return then([func](Try<T>&& t) {
142 return (*func)(std::move(t));
146 /// Variant where func returns a Future<R> instead of a R. e.g.
149 /// Future<R> doWork(Try<T>&&); }
151 /// Future<R> f2 = f1.then(&Worker::doWork);
152 template <class = T, class R = std::nullptr_t>
153 typename std::enable_if<isFuture<R>::value, R>::type
154 inline then(R(*func)(Try<T>&&)) {
155 return then([func](Try<T>&& t) {
156 return (*func)(std::move(t));
160 /// Variant where func is an member function
163 /// R doWork(Try<T>&&); }
166 /// Future<R> f2 = f1.then(w, &Worker::doWork);
167 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
168 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
169 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
170 return then([instance, func](Try<T>&& t) {
171 return (instance->*func)(std::move(t));
175 /// Variant where func returns a Future<R> instead of a R. e.g.
178 /// Future<R> doWork(Try<T>&&); }
181 /// Future<R> f2 = f1.then(w, &Worker::doWork);
182 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
183 typename std::enable_if<isFuture<R>::value, R>::type
184 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
185 return then([instance, func](Try<T>&& t) {
186 return (instance->*func)(std::move(t));
190 /// Convenience method for ignoring the value and creating a Future<void>.
191 /// Exceptions still propagate.
194 /// This is not the method you're looking for.
196 /// This needs to be public because it's used by make* and when*, and it's
197 /// not worth listing all those and their fancy template signatures as
198 /// friends. But it's not for public consumption.
200 void setCallback_(F&& func);
202 /// A Future's callback is executed when all three of these conditions have
203 /// become true: it has a value (set by the Promise), it has a callback (set
204 /// by then), and it is active (active by default).
206 /// Inactive Futures will activate upon destruction.
214 return core_->isActive();
218 void raise(E&& exception) {
219 raise(std::make_exception_ptr(std::forward<E>(exception)));
222 /// Raise an interrupt. If the promise holder has an interrupt
223 /// handler it will be called and potentially stop asynchronous work from
224 /// being done. This is advisory only - a promise holder may not set an
225 /// interrupt handler, or may do anything including ignore. But, if you know
226 /// your future supports this the most likely result is stopping or
227 /// preventing the asynchronous operation (if in time), and the promise
228 /// holder setting an exception on the future. (That may happen
229 /// asynchronously, of course.)
230 void raise(std::exception_ptr interrupt);
233 raise(FutureCancellation());
237 typedef detail::Core<T>* corePtr;
239 // shared core state object
243 Future(corePtr obj) : core_(obj) {}
247 void throwIfInvalid() const;
249 friend class Promise<T>;
253 Make a completed Future by moving in a value. e.g.
256 auto f = makeFuture(std::move(foo));
260 auto f = makeFuture<string>("foo");
263 Future<typename std::decay<T>::type> makeFuture(T&& t);
265 /** Make a completed void Future. */
266 Future<void> makeFuture();
268 /** Make a completed Future by executing a function. If the function throws
269 we capture the exception, otherwise we capture the result. */
273 typename std::enable_if<
274 !std::is_reference<F>::value, bool>::type sdf = false)
275 -> Future<decltype(func())>;
280 -> Future<decltype(func())>;
282 /// Make a failed Future from an exception_ptr.
283 /// Because the Future's type cannot be inferred you have to specify it, e.g.
285 /// auto f = makeFuture<string>(std::current_exception());
287 Future<T> makeFuture(std::exception_ptr const& e);
289 /** Make a Future from an exception type E that can be passed to
290 std::make_exception_ptr(). */
291 template <class T, class E>
292 typename std::enable_if<std::is_base_of<std::exception, E>::value,
294 makeFuture(E const& e);
296 /** Make a Future out of a Try */
298 Future<T> makeFuture(Try<T>&& t);
300 /** When all the input Futures complete, the returned Future will complete.
301 Errors do not cause early termination; this Future will always succeed
302 after all its Futures have finished (whether successfully or with an
305 The Futures are moved in, so your copies are invalid. If you need to
306 chain further from these Futures, use the variant with an output iterator.
308 XXX is this still true?
309 This function is thread-safe for Futures running on different threads.
311 The return type for Future<T> input is a Future<std::vector<Try<T>>>
313 template <class InputIterator>
314 Future<std::vector<Try<
315 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
316 whenAll(InputIterator first, InputIterator last);
318 /// This version takes a varying number of Futures instead of an iterator.
319 /// The return type for (Future<T1>, Future<T2>, ...) input
320 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
321 /// The Futures are moved in, so your copies are invalid.
322 template <typename... Fs>
323 typename detail::VariadicContext<
324 typename std::decay<Fs>::type::value_type...>::type
327 /** The result is a pair of the index of the first Future to complete and
328 the Try. If multiple Futures complete at the same time (or are already
329 complete when passed in), the "winner" is chosen non-deterministically.
331 This function is thread-safe for Futures running on different threads.
333 template <class InputIterator>
336 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
337 whenAny(InputIterator first, InputIterator last);
339 /** when n Futures have completed, the Future completes with a vector of
340 the index and Try of those n Futures (the indices refer to the original
341 order, but the result vector will be in an arbitrary order)
345 template <class InputIterator>
346 Future<std::vector<std::pair<
348 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
349 whenN(InputIterator first, InputIterator last, size_t n);
351 /** Wait for the given future to complete on a semaphore. Returns a completed
352 * future containing the result.
354 * NB if the promise for the future would be fulfilled in the same thread that
355 * you call this, it will deadlock.
358 Future<T> waitWithSemaphore(Future<T>&& f);
360 /** Wait for up to `timeout` for the given future to complete. Returns a future
361 * which may or may not be completed depending whether the given future
364 * Note: each call to this starts a (short-lived) thread and allocates memory.
366 template <typename T, class Duration>
367 Future<T> waitWithSemaphore(Future<T>&& f, Duration timeout);
371 #include <folly/wangle/Future-inl.h>