1 /* Copyright (c) 2016-2018. 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 mast 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 becase 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 * implicitely 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 {
146 void set_value(T value)
148 if (this->get_status() != FutureStatus::not_ready)
149 throw std::future_error(std::future_errc::promise_already_satisfied);
150 value_ = std::move(value);
157 xbt_assert(this->value_);
158 auto result = std::move(this->value_.get());
159 this->value_ = boost::optional<T>();
160 return std::move(result);
164 boost::optional<T> value_;
168 class FutureState<T&> : public FutureStateBase {
170 void set_value(T& value)
172 if (this->get_status() != FutureStatus::not_ready)
173 throw std::future_error(std::future_errc::promise_already_satisfied);
181 xbt_assert(this->value_);
192 class FutureState<void> : public FutureStateBase {
196 if (this->get_status() != FutureStatus::not_ready)
197 throw std::future_error(std::future_errc::promise_already_satisfied);
207 template <class T> void bind_promise(Promise<T> promise, Future<T> future)
209 class PromiseBinder {
211 explicit PromiseBinder(Promise<T> promise) : promise_(std::move(promise)) {}
212 void operator()(Future<T> future) { simgrid::xbt::set_promise(promise_, future); }
217 future.then_(PromiseBinder(std::move(promise)));
220 template <class T> Future<T> unwrap_future(Future<Future<T>> future);
223 XBT_ATTRIB_DEPRECATED_v323("Please use bind_promise") void bindPromise(Promise<T> promise, Future<T> future)
225 bind_promise(promise, future);
228 XBT_ATTRIB_DEPRECATED_v323("Please use unwrap_future") Future<T> unwrapFuture(Future<Future<T>> future)
230 unwrap_future(future);
233 /** Result of some (probably) asynchronous operation in the SimGrid kernel
235 * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
236 * abstration for asynchronous stuff happening in the SimGrid kernel. They
237 * are based on C++1z futures.
239 * The future represents a value which will be available at some point when this
240 * asynchronous operaiont is finished. Alternatively, if this operations fails,
241 * the result of the operation might be an exception.
243 * As the operation is possibly no terminated yet, we cannot get the result
244 * yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
245 * it. However, we can attach some code/callback/continuation which will be
246 * executed when the operation terminates.
248 * Example of the API (`simgrid::kernel::createProcess` does not exist):
250 * // Create a new process using the Worker code, this process returns
252 * simgrid::kernel::Future<std::string> future =
253 * simgrid::kernel::createProcess("worker42", host, Worker(42));
254 * // At this point, we just created the process so the result is not available.
255 * // However, we can attach some work do be done with this result:
256 * future.then([](simgrid::kernel::Future<std::string> result) {
257 * // This code is called when the operation is completed so the result is
260 * // Try to get value, this might throw an exception if the operation
261 * // failed (such as an exception throwed by the worker process):
262 * std::string value = result.get();
263 * XBT_INFO("Value: %s", value.c_str());
265 * catch(std::exception& e) {
266 * // This is an exception from the asynchronous operation:
267 * XBT_INFO("Error: %e", e.what());
272 * This is based on C++1z std::future but with some differences:
274 * * there is no thread synchronization (atomic, mutex, condition variable,
275 * etc.) because everything happens in the SimGrid event loop;
277 * * it is purely asynchronous, you are expected to use `.then()`;
279 * * inside the `.then()`, `.get()` can be used;
281 * * `.get()` can only be used when `.is_ready()` (as everything happens in
282 * a single-thread, the future would be guaranted to deadlock if `.get()`
283 * is called when the future is not ready);
285 * * there is no future chaining support for now (`.then().then()`);
287 * * there is no sharing (`shared_future`) for now.
293 explicit Future(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
296 Future(Future&) = delete;
297 Future& operator=(Future&) = delete;
298 Future(Future&& that) : state_(std::move(that.state_)) {}
299 Future& operator=(Future&& that)
301 state_ = std::move(that.state_);
305 /** Whether the future is valid:.
307 * A future which as been used (`.then` of `.get`) becomes invalid.
309 * We can use `.then` on a valid future.
313 return state_ != nullptr;
316 /** Whether the future is ready
318 * A future is ready when it has an associated value or exception.
320 * We can use `.get()` on ready futures.
322 bool is_ready() const
324 return state_ != nullptr && state_->is_ready();
327 /** Attach a continuation to this future
329 * This is like .then() but avoid the creation of a new future.
332 void then_(F continuation)
334 if (state_ == nullptr)
335 throw std::future_error(std::future_errc::no_state);
336 // Give shared-ownership to the continuation:
337 auto state = std::move(state_);
338 state->set_continuation(simgrid::xbt::make_task(std::move(continuation), state));
341 /** Attach a continuation to this future
343 * This version never does future unwrapping.
345 template <class F> auto then_no_unwrap(F continuation) -> Future<decltype(continuation(std::move(*this)))>
347 typedef decltype(continuation(std::move(*this))) R;
348 if (state_ == nullptr)
349 throw std::future_error(std::future_errc::no_state);
350 auto state = std::move(state_);
351 // Create a new future...
353 Future<R> future = promise.get_future();
354 // ...and when the current future is ready...
355 state->set_continuation(simgrid::xbt::make_task(
356 [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
357 // ...set the new future value by running the continuation.
358 Future<T> future(std::move(state));
359 simgrid::xbt::fulfill_promise(promise, [&] { return continuation(std::move(future)); });
361 std::move(promise), state, std::move(continuation)));
362 return std::move(future);
366 XBT_ATTRIB_DEPRECATED_v323("Please use then_no_unwrap") auto thenNoUnwrap(F continuation)
367 -> Future<decltype(continuation(std::move(*this)))>
369 then_no_unwrap(continuation);
372 /** Attach a continuation to this future
374 * The future must be valid in order to make this call.
375 * The continuation is executed when the future becomes ready.
376 * The future becomes invalid after this call.
378 * @param continuation This function is called with a ready future
379 * the future is ready
380 * @exception std::future_error no state is associated with the future
383 auto then(F continuation) -> typename std::enable_if<not is_future<decltype(continuation(std::move(*this)))>::value,
384 Future<decltype(continuation(std::move(*this)))>>::type
386 return this->then_no_unwrap(std::move(continuation));
389 /** Attach a continuation to this future (future chaining) */
391 auto then(F continuation)
392 -> typename std::enable_if<
393 is_future<decltype(continuation(std::move(*this)))>::value,
394 decltype(continuation(std::move(*this)))
397 return unwrap_future(this->then_no_unwrap(std::move(continuation)));
400 /** Get the value from the future
402 * The future must be valid and ready in order to make this call.
403 * std::future blocks when the future is not ready but we are
404 * completely single-threaded so blocking would be a deadlock.
405 * After the call, the future becomes invalid.
407 * @return value of the future
408 * @exception any Exception from the future
409 * @exception std::future_error no state is associated with the future
413 if (state_ == nullptr)
414 throw std::future_error(std::future_errc::no_state);
415 std::shared_ptr<FutureState<T>> state = std::move(state_);
420 std::shared_ptr<FutureState<T>> state_;
423 template <class T> Future<T> unwrap_future(Future<Future<T>> future)
426 Future<T> result = promise.get_future();
427 bind_promise(std::move(promise), std::move(future));
428 return std::move(result);
431 /** Producer side of a @ref simgrid::kernel::Future
433 * A @ref Promise is connected to some `Future` and can be used to
436 * Similar to std::promise
439 * // Create a promise and a future:
440 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
441 * auto future = promise->get_future();
443 * SIMIX_timer_set(date, [promise] {
445 * int value = compute_the_value();
447 * throw std::logic_error("Bad value");
448 * // Whenever the operation is completed, we set the value
450 * promise.set_value(value);
453 * // If an error occured, we can set an exception which
454 * // will be throwed buy future.get():
455 * promise.set_exception(std::current_exception());
459 * // Return the future to the caller:
466 Promise() : state_(std::make_shared<FutureState<T>>()) {}
467 explicit Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
470 Promise(Promise const&) = delete;
471 Promise& operator=(Promise const&) = delete;
472 Promise(Promise&& that) :
473 state_(std::move(that.state_)), future_get_(that.future_get_)
475 that.future_get_ = false;
478 Promise& operator=(Promise&& that)
480 this->state_ = std::move(that.state_);
481 this->future_get_ = that.future_get_;
482 that.future_get_ = false;
485 Future<T> get_future()
487 if (state_ == nullptr)
488 throw std::future_error(std::future_errc::no_state);
490 throw std::future_error(std::future_errc::future_already_retrieved);
492 return Future<T>(state_);
494 void set_value(T value)
496 if (state_ == nullptr)
497 throw std::future_error(std::future_errc::no_state);
498 state_->set_value(std::move(value));
500 void set_exception(std::exception_ptr exception)
502 if (state_ == nullptr)
503 throw std::future_error(std::future_errc::no_state);
504 state_->set_exception(std::move(exception));
508 if (state_ && state_->get_status() == FutureStatus::not_ready)
509 state_->set_exception(std::make_exception_ptr(
510 std::future_error(std::future_errc::broken_promise)));
514 std::shared_ptr<FutureState<T>> state_;
515 bool future_get_ = false;
519 class Promise<void> {
521 Promise() : state_(std::make_shared<FutureState<void>>()) {}
522 explicit Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
525 if (state_ && state_->get_status() == FutureStatus::not_ready)
526 state_->set_exception(std::make_exception_ptr(
527 std::future_error(std::future_errc::broken_promise)));
531 Promise(Promise const&) = delete;
532 Promise& operator=(Promise const&) = delete;
533 Promise(Promise&& that) :
534 state_(std::move(that.state_)), future_get_(that.future_get_)
536 that.future_get_ = false;
538 Promise& operator=(Promise&& that)
540 this->state_ = std::move(that.state_);
541 this->future_get_ = that.future_get_;
542 that.future_get_ = false;
546 Future<void> get_future()
548 if (state_ == nullptr)
549 throw std::future_error(std::future_errc::no_state);
551 throw std::future_error(std::future_errc::future_already_retrieved);
553 return Future<void>(state_);
557 if (state_ == nullptr)
558 throw std::future_error(std::future_errc::no_state);
561 void set_exception(std::exception_ptr exception)
563 if (state_ == nullptr)
564 throw std::future_error(std::future_errc::no_state);
565 state_->set_exception(std::move(exception));
569 std::shared_ptr<FutureState<void>> state_;
570 bool future_get_ = false;