1 /* Copyright (c) 2016-2019. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 #ifndef SIMGRID_KERNEL_FUTURE_HPP
8 #define SIMGRID_KERNEL_FUTURE_HPP
14 #include <type_traits>
16 #include <boost/optional.hpp>
19 #include <xbt/functional.hpp>
20 #include <xbt/future.hpp>
25 // There are the public classes:
26 template<class T> class Future;
27 template<class T> class Promise;
29 // Those are implementation details:
30 enum class FutureStatus;
31 template<class T> class FutureState;
33 enum class FutureStatus {
40 struct is_future : std::false_type {};
42 struct is_future<Future<T>> : std::true_type {};
44 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
45 class FutureStateBase {
48 FutureStateBase(FutureStateBase const&) = delete;
49 FutureStateBase& operator=(FutureStateBase const&) = delete;
51 XBT_PUBLIC void schedule(simgrid::xbt::Task<void()>&& job);
53 void set_exception(std::exception_ptr exception)
55 xbt_assert(exception_ == nullptr);
56 if (status_ != FutureStatus::not_ready)
57 throw std::future_error(std::future_errc::promise_already_satisfied);
58 exception_ = std::move(exception);
62 void set_continuation(simgrid::xbt::Task<void()>&& continuation)
64 xbt_assert(not continuation_);
66 case FutureStatus::done:
67 // This is not supposed to happen if continuation is set
69 xbt_die("Set continuation on finished future");
71 case FutureStatus::ready:
72 // The future is ready, execute the continuation directly.
73 // We might execute it from the event loop instead:
74 schedule(std::move(continuation));
76 case FutureStatus::not_ready:
77 // The future is not ready so we must keep the continuation for
78 // executing it later:
79 continuation_ = std::move(continuation);
86 FutureStatus get_status() const
93 return status_ == FutureStatus::ready;
97 FutureStateBase() = default;
98 ~FutureStateBase() = default;
100 /** Set the future as ready and trigger the continuation */
103 status_ = FutureStatus::ready;
105 // We unregister the continuation before executing it.
106 // We need to do this because the current implementation of the
107 // continuation has a shared_ptr to the FutureState.
108 auto continuation = std::move(continuation_);
109 this->schedule(std::move(continuation));
113 /** Set the future as done and raise an exception if any
115 * This does half the job of `.get()`.
119 if (status_ != FutureStatus::ready)
120 xbt_die("Deadlock: this future is not ready");
121 status_ = FutureStatus::done;
123 std::exception_ptr exception = std::move(exception_);
124 exception_ = nullptr;
125 std::rethrow_exception(std::move(exception));
130 FutureStatus status_ = FutureStatus::not_ready;
131 std::exception_ptr exception_;
132 simgrid::xbt::Task<void()> continuation_;
135 /** Shared state for future and promises
137 * You are not expected to use them directly but to create them
138 * implicitly through a @ref simgrid::kernel::Promise.
139 * Alternatively kernel operations could inherit or contain FutureState
140 * if they are managed with std::shared_ptr.
143 class FutureState : public FutureStateBase {
145 void set_value(T value)
147 if (this->get_status() != FutureStatus::not_ready)
148 throw std::future_error(std::future_errc::promise_already_satisfied);
149 value_ = std::move(value);
156 xbt_assert(this->value_);
157 auto result = std::move(this->value_.get());
158 this->value_ = boost::optional<T>();
163 boost::optional<T> value_;
167 class FutureState<T&> : public FutureStateBase {
169 void set_value(T& value)
171 if (this->get_status() != FutureStatus::not_ready)
172 throw std::future_error(std::future_errc::promise_already_satisfied);
180 xbt_assert(this->value_);
191 class FutureState<void> : public FutureStateBase {
195 if (this->get_status() != FutureStatus::not_ready)
196 throw std::future_error(std::future_errc::promise_already_satisfied);
206 template <class T> void bind_promise(Promise<T>&& promise, Future<T> future)
208 class PromiseBinder {
210 explicit PromiseBinder(Promise<T>&& promise) : promise_(std::move(promise)) {}
211 void operator()(Future<T> future) { simgrid::xbt::set_promise(promise_, future); }
216 future.then_(PromiseBinder(std::move(promise)));
219 template <class T> Future<T> unwrap_future(Future<Future<T>> future);
221 /** Result of some (probably) asynchronous operation in the SimGrid kernel
223 * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
224 * abstraction for asynchronous stuff happening in the SimGrid kernel. They
225 * are based on C++1z futures.
227 * The future represents a value which will be available at some point when this
228 * asynchronous operation is finished. Alternatively, if this operations fails,
229 * the result of the operation might be an exception.
231 * As the operation is possibly no terminated yet, we cannot get the result
232 * yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
233 * it. However, we can attach some code/callback/continuation which will be
234 * executed when the operation terminates.
236 * Example of the API (`simgrid::kernel::createProcess` does not exist):
238 * // Create a new process using the Worker code, this process returns
240 * simgrid::kernel::Future<std::string> future =
241 * simgrid::kernel::createProcess("worker42", host, Worker(42));
242 * // At this point, we just created the process so the result is not available.
243 * // However, we can attach some work do be done with this result:
244 * future.then([](simgrid::kernel::Future<std::string> result) {
245 * // This code is called when the operation is completed so the result is
248 * // Try to get value, this might throw an exception if the operation
249 * // failed (such as an exception thrown by the worker process):
250 * std::string value = result.get();
251 * XBT_INFO("Value: %s", value.c_str());
253 * catch(std::exception& e) {
254 * // This is an exception from the asynchronous operation:
255 * XBT_INFO("Error: %e", e.what());
260 * This is based on C++1z std::future but with some differences:
262 * * there is no thread synchronization (atomic, mutex, condition variable,
263 * etc.) because everything happens in the SimGrid event loop;
265 * * it is purely asynchronous, you are expected to use `.then()`;
267 * * inside the `.then()`, `.get()` can be used;
269 * * `.get()` can only be used when `.is_ready()` (as everything happens in
270 * a single-thread, the future would be guaranteed to deadlock if `.get()`
271 * is called when the future is not ready);
273 * * there is no future chaining support for now (`.then().then()`);
275 * * there is no sharing (`shared_future`) for now.
281 explicit Future(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
285 Future(Future&) = delete;
286 Future& operator=(Future&) = delete;
287 Future(Future&& that) : state_(std::move(that.state_)) {}
288 Future& operator=(Future&& that)
290 state_ = std::move(that.state_);
294 /** Whether the future is valid:.
296 * A future which as been used (`.then` of `.get`) becomes invalid.
298 * We can use `.then` on a valid future.
302 return state_ != nullptr;
305 /** Whether the future is ready
307 * A future is ready when it has an associated value or exception.
309 * We can use `.get()` on ready futures.
311 bool is_ready() const
313 return state_ != nullptr && state_->is_ready();
316 /** Attach a continuation to this future
318 * This is like .then() but avoid the creation of a new future.
321 void then_(F continuation)
323 if (state_ == nullptr)
324 throw std::future_error(std::future_errc::no_state);
325 // Give shared-ownership to the continuation:
326 auto state = std::move(state_);
327 state->set_continuation(simgrid::xbt::make_task(std::move(continuation), state));
330 /** Attach a continuation to this future
332 * This version never does future unwrapping.
334 template <class F> auto then_no_unwrap(F continuation) -> Future<decltype(continuation(std::move(*this)))>
336 typedef decltype(continuation(std::move(*this))) R;
337 if (state_ == nullptr)
338 throw std::future_error(std::future_errc::no_state);
339 auto state = std::move(state_);
340 // Create a new future...
342 Future<R> future = promise.get_future();
343 // ...and when the current future is ready...
344 state->set_continuation(simgrid::xbt::make_task(
345 [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
346 // ...set the new future value by running the continuation.
347 Future<T> future(std::move(state));
348 simgrid::xbt::fulfill_promise(promise, [&continuation, &future] { return continuation(std::move(future)); });
350 std::move(promise), state, std::move(continuation)));
354 /** Attach a continuation to this future
356 * The future must be valid in order to make this call.
357 * The continuation is executed when the future becomes ready.
358 * The future becomes invalid after this call.
360 * @param continuation This function is called with a ready future
361 * the future is ready
362 * @exception std::future_error no state is associated with the future
365 auto then(F continuation) -> typename std::enable_if<not is_future<decltype(continuation(std::move(*this)))>::value,
366 Future<decltype(continuation(std::move(*this)))>>::type
368 return this->then_no_unwrap(std::move(continuation));
371 /** Attach a continuation to this future (future chaining) */
373 auto then(F continuation)
374 -> typename std::enable_if<
375 is_future<decltype(continuation(std::move(*this)))>::value,
376 decltype(continuation(std::move(*this)))
379 return unwrap_future(this->then_no_unwrap(std::move(continuation)));
382 /** Get the value from the future
384 * The future must be valid and ready in order to make this call.
385 * std::future blocks when the future is not ready but we are
386 * completely single-threaded so blocking would be a deadlock.
387 * After the call, the future becomes invalid.
389 * @return value of the future
390 * @exception any Exception from the future
391 * @exception std::future_error no state is associated with the future
395 if (state_ == nullptr)
396 throw std::future_error(std::future_errc::no_state);
397 std::shared_ptr<FutureState<T>> state = std::move(state_);
402 std::shared_ptr<FutureState<T>> state_;
405 template <class T> Future<T> unwrap_future(Future<Future<T>> future)
408 Future<T> result = promise.get_future();
409 bind_promise(std::move(promise), std::move(future));
413 /** Producer side of a @ref simgrid::kernel::Future
415 * A @ref Promise is connected to some `Future` and can be used to
418 * Similar to std::promise
421 * // Create a promise and a future:
422 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
423 * auto future = promise->get_future();
425 * simgrid::simix::Timer::set(date, [promise] {
427 * int value = compute_the_value();
429 * throw std::logic_error("Bad value");
430 * // Whenever the operation is completed, we set the value
432 * promise.set_value(value);
435 * // If an error occurred, we can set an exception which
436 * // will be thrown by future.get():
437 * promise.set_exception(std::current_exception());
441 * // Return the future to the caller:
449 explicit Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
452 Promise(Promise const&) = delete;
453 Promise& operator=(Promise const&) = delete;
454 Promise(Promise&& that) : state_(std::move(that.state_)) { std::swap(future_get_, that.future_get_); }
456 Promise& operator=(Promise&& that)
458 this->state_ = std::move(that.state_);
459 this->future_get_ = that.future_get_;
460 that.future_get_ = false;
463 Future<T> get_future()
465 if (state_ == nullptr)
466 throw std::future_error(std::future_errc::no_state);
468 throw std::future_error(std::future_errc::future_already_retrieved);
470 return Future<T>(state_);
472 void set_value(T value)
474 if (state_ == nullptr)
475 throw std::future_error(std::future_errc::no_state);
476 state_->set_value(std::move(value));
478 void set_exception(std::exception_ptr exception)
480 if (state_ == nullptr)
481 throw std::future_error(std::future_errc::no_state);
482 state_->set_exception(std::move(exception));
486 if (state_ && state_->get_status() == FutureStatus::not_ready)
487 state_->set_exception(std::make_exception_ptr(
488 std::future_error(std::future_errc::broken_promise)));
492 std::shared_ptr<FutureState<T>> state_{new FutureState<T>()};
493 bool future_get_ = false;
497 class Promise<void> {
500 explicit Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
503 if (state_ && state_->get_status() == FutureStatus::not_ready)
504 state_->set_exception(std::make_exception_ptr(
505 std::future_error(std::future_errc::broken_promise)));
509 Promise(Promise const&) = delete;
510 Promise& operator=(Promise const&) = delete;
511 Promise(Promise&& that) : state_(std::move(that.state_)) { std::swap(future_get_, that.future_get_); }
512 Promise& operator=(Promise&& that)
514 this->state_ = std::move(that.state_);
515 this->future_get_ = that.future_get_;
516 that.future_get_ = false;
520 Future<void> get_future()
522 if (state_ == nullptr)
523 throw std::future_error(std::future_errc::no_state);
525 throw std::future_error(std::future_errc::future_already_retrieved);
527 return Future<void>(state_);
531 if (state_ == nullptr)
532 throw std::future_error(std::future_errc::no_state);
535 void set_exception(std::exception_ptr exception)
537 if (state_ == nullptr)
538 throw std::future_error(std::future_errc::no_state);
539 state_->set_exception(std::move(exception));
543 std::shared_ptr<FutureState<void>> state_{new FutureState<void>()};
544 bool future_get_ = false;