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
10 #include <boost/optional.hpp>
18 #include <type_traits>
23 // There are the public classes:
24 template<class T> class Future;
25 template<class T> class Promise;
27 // Those are implementation details:
28 enum class FutureStatus;
29 template<class T> class FutureState;
30 class FutureContinuation;
31 template<class T, class F> class FutureContinuationImpl;
33 enum class FutureStatus {
39 /** A continuation attached to a future to be executed when it is ready */
40 XBT_PUBLIC_CLASS FutureContinuation {
42 FutureContinuation() {}
45 FutureContinuation(FutureContinuation&) = delete;
46 FutureContinuation& operator=(FutureContinuation&) = delete;
48 virtual ~FutureContinuation() {}
49 virtual void operator()() = 0;
52 /** Default implementation of `FutureContinuation`
54 * @param T value type of the future
55 * @param F type of the wrapped code/callback/continuation
57 template<class T, class F>
58 class FutureContinuationImpl : public FutureContinuation {
60 FutureContinuationImpl(std::shared_ptr<FutureState<T>> ptr, F callback)
61 : ptr_(std::move(ptr)), callback_(std::move(callback)) {}
62 ~FutureContinuationImpl() override {}
63 void operator()() override
66 callback_(Future<T>(ptr_));
68 // Those exceptions are lost.
69 // If we want to implement callback chaining, we'll have to catch them and
70 // foward them to the next future.
76 std::shared_ptr<FutureState<T>> ptr_;
80 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
81 class FutureStateBase {
84 FutureStateBase(FutureStateBase const&) = delete;
85 FutureStateBase& operator=(FutureStateBase const&) = delete;
87 void set_exception(std::exception_ptr exception)
89 xbt_assert(exception_ == nullptr);
90 if (status_ != FutureStatus::not_ready)
91 throw std::future_error(std::future_errc::promise_already_satisfied);
92 exception_ = std::move(exception);
96 void set_continuation(std::unique_ptr<FutureContinuation> continuation)
98 xbt_assert(!continuation_);
100 case FutureStatus::done:
101 // This is not supposed to happen if continuation is set
103 xbt_die("Set continuation on finished future");
105 case FutureStatus::ready:
106 // The future is ready, execute the continuation directly.
107 // We might execute it from the event loop instead:
110 case FutureStatus::not_ready:
111 // The future is not ready so we mast keep the continuation for
112 // executing it later:
113 continuation_ = std::move(continuation);
118 FutureStatus get_status() const
123 bool is_ready() const
125 return status_ == FutureStatus::ready;
130 ~FutureStateBase() {};
132 /** Set the future as ready and trigger the continuation */
135 status_ = FutureStatus::ready;
137 // We unregister the continuation before executing it.
138 // We need to do this becase the current implementation of the
139 // continuation has a shared_ptr to the FutureState.
140 auto continuation = std::move(continuation_);
145 /** Set the future as done and raise an exception if any
147 * This does half the job of `.get()`.
151 if (status_ != FutureStatus::ready)
152 xbt_die("Deadlock: this future is not ready");
153 status_ = FutureStatus::done;
155 std::exception_ptr exception = std::move(exception_);
156 std::rethrow_exception(std::move(exception));
161 FutureStatus status_ = FutureStatus::not_ready;
162 std::exception_ptr exception_;
163 std::unique_ptr<FutureContinuation> continuation_;
166 /** Shared state for future and promises
168 * You are not expected to use them directly but to create them
169 * implicitely through a @ref simgrid::kernel::Promise.
170 * Alternatively kernel operations could inherit or contain FutureState
171 * if they are managed with @ref std::shared_ptr.
174 class FutureState : public FutureStateBase {
177 void set_value(T value)
179 if (this->get_status() != FutureStatus::not_ready)
180 throw std::future_error(std::future_errc::promise_already_satisfied);
181 value_ = std::move(value);
188 xbt_assert(this->value_);
189 auto result = std::move(this->value_.get());
190 this->value_ = boost::optional<T>();
191 return std::move(result);
195 boost::optional<T> value_;
199 class FutureState<T&> : public FutureStateBase {
201 void set_value(T& value)
203 if (this->get_status() != FutureStatus::not_ready)
204 throw std::future_error(std::future_errc::promise_already_satisfied);
212 xbt_assert(this->value_);
223 class FutureState<void> : public FutureStateBase {
227 if (this->get_status() != FutureStatus::not_ready)
228 throw std::future_error(std::future_errc::promise_already_satisfied);
238 /** Result of some (possibly ongoing, asynchronous) operation in the SimGrid kernel
240 * As the operation may not be completed yet, the result might be an exception.
242 * Example of the API (`simgrid::kernel::createProcess` does not exist):
244 * // Create a new process using the Worker code, this process returns
246 * simgrid::kernel::Future<std::string> future =
247 * simgrid::kernel::createProcess("worker42", host, Worker(42));
248 * // At this point, we just created the process so the result is not available.
249 * // However, we can attach some work do be done with this result:
250 * future.then([](simgrid::kernel::Future<std::string> result) {
251 * // This code is called when the operation is completed so the result is
254 * // Try to get value, this might throw an exception if the operation
255 * // failed (such as an exception throwed by the worker process):
256 * std::string value = result.get();
257 * XBT_INFO("Value: %s", value.c_str());
259 * catch(std::exception& e) {
260 * // This is an exception from the asynchronous operation:
261 * XBT_INFO("Error: %e", e.what());
266 * This is based on C++1z @ref std::future but with some differences:
268 * * there is no thread synchronization (atomic, mutex, condition variable,
269 * etc.) because everything happens in the SimGrid event loop;
271 * * it is purely asynchronous, you are expected to use `.then()`;
273 * * inside the `.then()`, `.get()` can be used;
275 * * `.get()` can only be used when `.is_ready()` (as everything happens in
276 * a single-thread, the future would be guaranted to deadlock if `.get()`
277 * is called when the future is not ready);
279 * * there is no future chaining support for now (`.then().then()`);
281 * * there is no sharing (`shared_future`) for now.
287 Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
290 Future(Future&) = delete;
291 Future& operator=(Future&) = delete;
292 Future(Future&& that) : state_(std::move(that.state_)) {}
293 Future& operator=(Future&& that)
295 state_ = std::move(that.stat_);
298 /** Whether the future is valid:.
300 * A future which as been used (`.then` of `.get`) becomes invalid.
302 * We can use `.then` on a valid future.
306 return state_ != nullptr;
309 /** Whether the future is ready
311 * A future is ready when it has an associated value or exception.
313 * We can use `.get()` on ready futures.
315 bool is_ready() const
317 return state_ != nullptr && state_->is_ready();
320 /** Attach a continuation to this future
322 * The future must be valid in order to make this call.
323 * The continuation is executed when the future becomes ready.
324 * The future becomes invalid after this call.
326 * We don't support future chaining for now (`.then().then()`).
328 * @param continuation This function is called with a ready future
329 * the future is ready
330 * @exception std::future_error no state is associated with the future
333 void then(F continuation)
335 if (state_ == nullptr)
336 throw std::future_error(std::future_errc::no_state);
337 std::unique_ptr<FutureContinuation> ptr =
338 std::unique_ptr<FutureContinuation>(
339 new FutureContinuationImpl<T,F>(state_, std::move(continuation)));
340 state_->set_continuation(std::move(ptr));
344 /** Get the value from the future
346 * This is expected to be called
348 * The future must be valid and ready in order to make this call.
349 * @ref std::future blocks when the future is not ready but we are
350 * completely single-threaded so blocking would be a deadlock.
351 * After the call, the future becomes invalid.
353 * @return value of the future
354 * @exception any Exception from the future
355 * @exception std::future_error no state is associated with the future
359 if (state_ == nullptr)
360 throw std::future_error(std::future_errc::no_state);
361 std::shared_ptr<FutureState<T>> state = std::move(state_);
366 std::shared_ptr<FutureState<T>> state_;
369 /** Producer side of a @simgrid::kernel::Future
371 * A @ref Promise is connected to some `Future` and can be used to
374 * Similar to @ref std::promise
377 * // Create a promise and a future:
378 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
379 * auto future = promise->get_future();
381 * SIMIX_timer_set(date, [promise] {
383 * int value = compute_the_value();
385 * throw std::logic_error("Bad value");
386 * // Whenever the operation is completed, we set the value
388 * promise.set_value(value);
391 * // If an error occured, we can set an exception which
392 * // will be throwed buy future.get():
393 * promise.set_exception(std::current_exception());
397 * // Return the future to the caller:
404 Promise() : state_(std::make_shared<FutureState<T>>()) {}
405 Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
408 Promise(Promise&) = delete;
409 Promise& operator=(Promise&) = delete;
410 Promise(Promise&& that) :
411 state_(std::move(that.state_)), future_get_(that.future_set)
413 that.future_get_ = false;
416 Promise& operator=(Promise&& that)
418 this->state_ = std::move(that.state_);
419 this->future_get_ = that.future_get_;
420 that.future_get_ = false;
423 Future<T> get_future()
425 if (state_ == nullptr)
426 throw std::future_error(std::future_errc::no_state);
428 throw std::future_error(std::future_errc::future_already_retrieved);
430 return Future<T>(state_);
432 void set_value(T value)
434 if (state_ == nullptr)
435 throw std::future_error(std::future_errc::no_state);
436 state_->set_value(std::move(value));
438 void set_exception(std::exception_ptr exception)
440 if (state_ == nullptr)
441 throw std::future_error(std::future_errc::no_state);
442 state_->set_exception(std::move(exception));
446 if (state_ && state_->get_status() == FutureStatus::not_ready)
447 state_->set_exception(std::make_exception_ptr(
448 std::future_error(std::future_errc::broken_promise)));
452 std::shared_ptr<FutureState<T>> state_;
453 bool future_get_ = false;
457 class Promise<void> {
459 Promise() : state_(std::make_shared<FutureState<void>>()) {}
460 Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
463 if (state_ && state_->get_status() == FutureStatus::not_ready)
464 state_->set_exception(std::make_exception_ptr(
465 std::future_error(std::future_errc::broken_promise)));
469 Promise(Promise&) = delete;
470 Promise& operator=(Promise&) = delete;
471 Promise(Promise&& that) :
472 state_(std::move(that.state_)), future_get_(that.future_get_)
474 that.future_get_ = false;
476 Promise& operator=(Promise&& that)
478 this->state_ = std::move(that.state_);
479 this->future_get_ = that.future_get_;
480 that.future_get_ = false;
484 Future<void> get_future()
486 if (state_ == nullptr)
487 throw std::future_error(std::future_errc::no_state);
489 throw std::future_error(std::future_errc::future_already_retrieved);
491 return Future<void>(state_);
495 if (state_ == nullptr)
496 throw std::future_error(std::future_errc::no_state);
499 void set_exception(std::exception_ptr exception)
501 if (state_ == nullptr)
502 throw std::future_error(std::future_errc::no_state);
503 state_->set_exception(std::move(exception));
507 std::shared_ptr<FutureState<void>> state_;
508 bool future_get_ = false;