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 typedef detail::Core<T>* corePtr;
220 // shared core state object
224 Future(corePtr obj) : core_(obj) {}
228 void throwIfInvalid() const;
230 friend class Promise<T>;
234 Make a completed Future by moving in a value. e.g.
237 auto f = makeFuture(std::move(foo));
241 auto f = makeFuture<string>("foo");
244 Future<typename std::decay<T>::type> makeFuture(T&& t);
246 /** Make a completed void Future. */
247 Future<void> makeFuture();
249 /** Make a completed Future by executing a function. If the function throws
250 we capture the exception, otherwise we capture the result. */
254 typename std::enable_if<
255 !std::is_reference<F>::value, bool>::type sdf = false)
256 -> Future<decltype(func())>;
261 -> Future<decltype(func())>;
263 /// Make a failed Future from an exception_ptr.
264 /// Because the Future's type cannot be inferred you have to specify it, e.g.
266 /// auto f = makeFuture<string>(std::current_exception());
268 Future<T> makeFuture(std::exception_ptr const& e);
270 /** Make a Future from an exception type E that can be passed to
271 std::make_exception_ptr(). */
272 template <class T, class E>
273 typename std::enable_if<std::is_base_of<std::exception, E>::value,
275 makeFuture(E const& e);
277 /** Make a Future out of a Try */
279 Future<T> makeFuture(Try<T>&& t);
281 /** When all the input Futures complete, the returned Future will complete.
282 Errors do not cause early termination; this Future will always succeed
283 after all its Futures have finished (whether successfully or with an
286 The Futures are moved in, so your copies are invalid. If you need to
287 chain further from these Futures, use the variant with an output iterator.
289 XXX is this still true?
290 This function is thread-safe for Futures running on different threads.
292 The return type for Future<T> input is a Future<std::vector<Try<T>>>
294 template <class InputIterator>
295 Future<std::vector<Try<
296 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
297 whenAll(InputIterator first, InputIterator last);
299 /// This version takes a varying number of Futures instead of an iterator.
300 /// The return type for (Future<T1>, Future<T2>, ...) input
301 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
302 /// The Futures are moved in, so your copies are invalid.
303 template <typename... Fs>
304 typename detail::VariadicContext<
305 typename std::decay<Fs>::type::value_type...>::type
308 /** The result is a pair of the index of the first Future to complete and
309 the Try. If multiple Futures complete at the same time (or are already
310 complete when passed in), the "winner" is chosen non-deterministically.
312 This function is thread-safe for Futures running on different threads.
314 template <class InputIterator>
317 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
318 whenAny(InputIterator first, InputIterator last);
320 /** when n Futures have completed, the Future completes with a vector of
321 the index and Try of those n Futures (the indices refer to the original
322 order, but the result vector will be in an arbitrary order)
326 template <class InputIterator>
327 Future<std::vector<std::pair<
329 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
330 whenN(InputIterator first, InputIterator last, size_t n);
332 /** Wait for the given future to complete on a semaphore. Returns a completed
333 * future containing the result.
335 * NB if the promise for the future would be fulfilled in the same thread that
336 * you call this, it will deadlock.
339 Future<T> waitWithSemaphore(Future<T>&& f);
341 /** Wait for up to `timeout` for the given future to complete. Returns a future
342 * which may or may not be completed depending whether the given future
345 * Note: each call to this starts a (short-lived) thread and allocates memory.
347 template <typename T, class Duration>
348 Future<T> waitWithSemaphore(Future<T>&& f, Duration timeout);
352 #include <folly/wangle/Future-inl.h>