1 /* Copyright (c) 2016. 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>
24 // There are the public classes:
25 template<class T> class Future;
26 template<class T> class Promise;
28 // Those are implementation details:
29 enum class FutureStatus;
30 template<class T> class FutureState;
32 enum class FutureStatus {
39 struct is_future : public std::integral_constant<bool, false> {};
41 struct is_future<Future<T>> : public std::integral_constant<bool, true> {};
43 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
44 class FutureStateBase {
47 FutureStateBase(FutureStateBase const&) = delete;
48 FutureStateBase& operator=(FutureStateBase const&) = delete;
50 void set_exception(std::exception_ptr exception)
52 xbt_assert(exception_ == nullptr);
53 if (status_ != FutureStatus::not_ready)
54 throw std::future_error(std::future_errc::promise_already_satisfied);
55 exception_ = std::move(exception);
59 void set_continuation(simgrid::xbt::Task<void()> continuation)
61 xbt_assert(!continuation_);
63 case FutureStatus::done:
64 // This is not supposed to happen if continuation is set
66 xbt_die("Set continuation on finished future");
68 case FutureStatus::ready:
69 // The future is ready, execute the continuation directly.
70 // We might execute it from the event loop instead:
73 case FutureStatus::not_ready:
74 // The future is not ready so we mast keep the continuation for
75 // executing it later:
76 continuation_ = std::move(continuation);
83 FutureStatus get_status() const
90 return status_ == FutureStatus::ready;
94 FutureStateBase() = default;
95 ~FutureStateBase() = default;
97 /** Set the future as ready and trigger the continuation */
100 status_ = FutureStatus::ready;
102 // We unregister the continuation before executing it.
103 // We need to do this becase the current implementation of the
104 // continuation has a shared_ptr to the FutureState.
105 auto continuation = std::move(continuation_);
110 /** Set the future as done and raise an exception if any
112 * This does half the job of `.get()`.
116 if (status_ != FutureStatus::ready)
117 xbt_die("Deadlock: this future is not ready");
118 status_ = FutureStatus::done;
120 std::exception_ptr exception = std::move(exception_);
121 std::rethrow_exception(std::move(exception));
126 FutureStatus status_ = FutureStatus::not_ready;
127 std::exception_ptr exception_;
128 simgrid::xbt::Task<void()> continuation_;
131 /** Shared state for future and promises
133 * You are not expected to use them directly but to create them
134 * implicitely through a @ref simgrid::kernel::Promise.
135 * Alternatively kernel operations could inherit or contain FutureState
136 * if they are managed with @ref std::shared_ptr.
139 class FutureState : public FutureStateBase {
142 void set_value(T value)
144 if (this->get_status() != FutureStatus::not_ready)
145 throw std::future_error(std::future_errc::promise_already_satisfied);
146 value_ = std::move(value);
153 xbt_assert(this->value_);
154 auto result = std::move(this->value_.get());
155 this->value_ = boost::optional<T>();
156 return std::move(result);
160 boost::optional<T> value_;
164 class FutureState<T&> : public FutureStateBase {
166 void set_value(T& value)
168 if (this->get_status() != FutureStatus::not_ready)
169 throw std::future_error(std::future_errc::promise_already_satisfied);
177 xbt_assert(this->value_);
188 class FutureState<void> : public FutureStateBase {
192 if (this->get_status() != FutureStatus::not_ready)
193 throw std::future_error(std::future_errc::promise_already_satisfied);
204 void bindPromise(Promise<T> promise, Future<T> future)
206 struct PromiseBinder {
208 PromiseBinder(Promise<T> promise) : promise_(std::move(promise)) {}
209 void operator()(Future<T> future)
211 simgrid::xbt::setPromise(promise_, future);
216 future.then_(PromiseBinder(std::move(promise)));
219 template<class T> Future<T> unwrapFuture(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 * abstration 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 operaiont 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 throwed 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 @ref 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 guaranted 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 Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
284 Future(Future&) = delete;
285 Future& operator=(Future&) = delete;
286 Future(Future&& that) : state_(std::move(that.state_)) {}
287 Future& operator=(Future&& that)
289 state_ = std::move(that.state_);
293 /** Whether the future is valid:.
295 * A future which as been used (`.then` of `.get`) becomes invalid.
297 * We can use `.then` on a valid future.
301 return state_ != nullptr;
304 /** Whether the future is ready
306 * A future is ready when it has an associated value or exception.
308 * We can use `.get()` on ready futures.
310 bool is_ready() const
312 return state_ != nullptr && state_->is_ready();
315 /** Attach a continuation to this future
317 * This is like .then() but avoid the creation of a new future.
320 void then_(F continuation)
322 if (state_ == nullptr)
323 throw std::future_error(std::future_errc::no_state);
324 // Give shared-ownership to the continuation:
325 auto state = std::move(state_);
326 state->set_continuation(simgrid::xbt::makeTask(
327 std::move(continuation), state));
330 /** Attach a continuation to this future
332 * This version never does future unwrapping.
335 auto thenNoUnwrap(F continuation)
336 -> Future<decltype(continuation(std::move(*this)))>
338 typedef decltype(continuation(std::move(*this))) R;
339 if (state_ == nullptr)
340 throw std::future_error(std::future_errc::no_state);
341 auto state = std::move(state_);
342 // Create a new future...
344 Future<R> future = promise.get_future();
345 // ...and when the current future is ready...
346 state->set_continuation(simgrid::xbt::makeTask(
347 [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
348 // ...set the new future value by running the continuation.
349 Future<T> future(std::move(state));
350 simgrid::xbt::fulfillPromise(promise,[&]{
351 return continuation(std::move(future));
354 std::move(promise), state, std::move(continuation)));
355 return std::move(future);
358 /** Attach a continuation to this future
360 * The future must be valid in order to make this call.
361 * The continuation is executed when the future becomes ready.
362 * The future becomes invalid after this call.
364 * @param continuation This function is called with a ready future
365 * the future is ready
366 * @exception std::future_error no state is associated with the future
369 auto then(F continuation)
370 -> typename std::enable_if<
371 !is_future<decltype(continuation(std::move(*this)))>::value,
372 Future<decltype(continuation(std::move(*this)))>
375 return this->thenNoUnwrap(std::move(continuation));
378 /** Attach a continuation to this future (future chaining) */
380 auto then(F continuation)
381 -> typename std::enable_if<
382 is_future<decltype(continuation(std::move(*this)))>::value,
383 decltype(continuation(std::move(*this)))
386 return unwrapFuture(this->thenNoUnwap(std::move(continuation)));
389 /** Get the value from the future
391 * This is expected to be called
393 * The future must be valid and ready in order to make this call.
394 * @ref std::future blocks when the future is not ready but we are
395 * completely single-threaded so blocking would be a deadlock.
396 * After the call, the future becomes invalid.
398 * @return value of the future
399 * @exception any Exception from the future
400 * @exception std::future_error no state is associated with the future
404 if (state_ == nullptr)
405 throw std::future_error(std::future_errc::no_state);
406 std::shared_ptr<FutureState<T>> state = std::move(state_);
411 std::shared_ptr<FutureState<T>> state_;
415 Future<T> unwrapFuture(Future<Future<T>> future)
418 Future<T> result = promise.get_future();
419 bindPromise(std::move(promise), std::move(future));
420 return std::move(result);
423 /** Producer side of a @simgrid::kernel::Future
425 * A @ref Promise is connected to some `Future` and can be used to
428 * Similar to @ref std::promise
431 * // Create a promise and a future:
432 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
433 * auto future = promise->get_future();
435 * SIMIX_timer_set(date, [promise] {
437 * int value = compute_the_value();
439 * throw std::logic_error("Bad value");
440 * // Whenever the operation is completed, we set the value
442 * promise.set_value(value);
445 * // If an error occured, we can set an exception which
446 * // will be throwed buy future.get():
447 * promise.set_exception(std::current_exception());
451 * // Return the future to the caller:
458 Promise() : state_(std::make_shared<FutureState<T>>()) {}
459 Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
462 Promise(Promise const&) = delete;
463 Promise& operator=(Promise const&) = delete;
464 Promise(Promise&& that) :
465 state_(std::move(that.state_)), future_get_(that.future_get_)
467 that.future_get_ = false;
470 Promise& operator=(Promise&& that)
472 this->state_ = std::move(that.state_);
473 this->future_get_ = that.future_get_;
474 that.future_get_ = false;
477 Future<T> get_future()
479 if (state_ == nullptr)
480 throw std::future_error(std::future_errc::no_state);
482 throw std::future_error(std::future_errc::future_already_retrieved);
484 return Future<T>(state_);
486 void set_value(T value)
488 if (state_ == nullptr)
489 throw std::future_error(std::future_errc::no_state);
490 state_->set_value(std::move(value));
492 void set_exception(std::exception_ptr exception)
494 if (state_ == nullptr)
495 throw std::future_error(std::future_errc::no_state);
496 state_->set_exception(std::move(exception));
500 if (state_ && state_->get_status() == FutureStatus::not_ready)
501 state_->set_exception(std::make_exception_ptr(
502 std::future_error(std::future_errc::broken_promise)));
506 std::shared_ptr<FutureState<T>> state_;
507 bool future_get_ = false;
511 class Promise<void> {
513 Promise() : state_(std::make_shared<FutureState<void>>()) {}
514 Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
517 if (state_ && state_->get_status() == FutureStatus::not_ready)
518 state_->set_exception(std::make_exception_ptr(
519 std::future_error(std::future_errc::broken_promise)));
523 Promise(Promise const&) = delete;
524 Promise& operator=(Promise const&) = delete;
525 Promise(Promise&& that) :
526 state_(std::move(that.state_)), future_get_(that.future_get_)
528 that.future_get_ = false;
530 Promise& operator=(Promise&& that)
532 this->state_ = std::move(that.state_);
533 this->future_get_ = that.future_get_;
534 that.future_get_ = false;
538 Future<void> get_future()
540 if (state_ == nullptr)
541 throw std::future_error(std::future_errc::no_state);
543 throw std::future_error(std::future_errc::future_already_retrieved);
545 return Future<void>(state_);
549 if (state_ == nullptr)
550 throw std::future_error(std::future_errc::no_state);
553 void set_exception(std::exception_ptr exception)
555 if (state_ == nullptr)
556 throw std::future_error(std::future_errc::no_state);
557 state_->set_exception(std::move(exception));
561 std::shared_ptr<FutureState<void>> state_;
562 bool future_get_ = false;