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 (probably) asynchronous operation in the SimGrid kernel
240 * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
241 * abstration for asynchronous stuff happening in the SimGrid kernel. They
242 * are based on C++1z futures.
244 * The future represents a value which will be available at some point when this
245 * asynchronous operaiont is finished. Alternatively, if this operations fails,
246 * the result of the operation might be an exception.
248 * As the operation is possibly no terminated yet, we cannot get the result
249 * yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
250 * it. However, we can attach some code/callback/continuation which will be
251 * executed when the operation terminates.
253 * Example of the API (`simgrid::kernel::createProcess` does not exist):
255 * // Create a new process using the Worker code, this process returns
257 * simgrid::kernel::Future<std::string> future =
258 * simgrid::kernel::createProcess("worker42", host, Worker(42));
259 * // At this point, we just created the process so the result is not available.
260 * // However, we can attach some work do be done with this result:
261 * future.then([](simgrid::kernel::Future<std::string> result) {
262 * // This code is called when the operation is completed so the result is
265 * // Try to get value, this might throw an exception if the operation
266 * // failed (such as an exception throwed by the worker process):
267 * std::string value = result.get();
268 * XBT_INFO("Value: %s", value.c_str());
270 * catch(std::exception& e) {
271 * // This is an exception from the asynchronous operation:
272 * XBT_INFO("Error: %e", e.what());
277 * This is based on C++1z @ref std::future but with some differences:
279 * * there is no thread synchronization (atomic, mutex, condition variable,
280 * etc.) because everything happens in the SimGrid event loop;
282 * * it is purely asynchronous, you are expected to use `.then()`;
284 * * inside the `.then()`, `.get()` can be used;
286 * * `.get()` can only be used when `.is_ready()` (as everything happens in
287 * a single-thread, the future would be guaranted to deadlock if `.get()`
288 * is called when the future is not ready);
290 * * there is no future chaining support for now (`.then().then()`);
292 * * there is no sharing (`shared_future`) for now.
298 Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
301 Future(Future&) = delete;
302 Future& operator=(Future&) = delete;
303 Future(Future&& that) : state_(std::move(that.state_)) {}
304 Future& operator=(Future&& that)
306 state_ = std::move(that.stat_);
309 /** Whether the future is valid:.
311 * A future which as been used (`.then` of `.get`) becomes invalid.
313 * We can use `.then` on a valid future.
317 return state_ != nullptr;
320 /** Whether the future is ready
322 * A future is ready when it has an associated value or exception.
324 * We can use `.get()` on ready futures.
326 bool is_ready() const
328 return state_ != nullptr && state_->is_ready();
331 /** Attach a continuation to this future
333 * The future must be valid in order to make this call.
334 * The continuation is executed when the future becomes ready.
335 * The future becomes invalid after this call.
337 * We don't support future chaining for now (`.then().then()`).
339 * @param continuation This function is called with a ready future
340 * the future is ready
341 * @exception std::future_error no state is associated with the future
344 void then(F continuation)
346 if (state_ == nullptr)
347 throw std::future_error(std::future_errc::no_state);
348 std::unique_ptr<FutureContinuation> ptr =
349 std::unique_ptr<FutureContinuation>(
350 new FutureContinuationImpl<T,F>(state_, std::move(continuation)));
351 state_->set_continuation(std::move(ptr));
355 /** Get the value from the future
357 * This is expected to be called
359 * The future must be valid and ready in order to make this call.
360 * @ref std::future blocks when the future is not ready but we are
361 * completely single-threaded so blocking would be a deadlock.
362 * After the call, the future becomes invalid.
364 * @return value of the future
365 * @exception any Exception from the future
366 * @exception std::future_error no state is associated with the future
370 if (state_ == nullptr)
371 throw std::future_error(std::future_errc::no_state);
372 std::shared_ptr<FutureState<T>> state = std::move(state_);
377 std::shared_ptr<FutureState<T>> state_;
380 /** Producer side of a @simgrid::kernel::Future
382 * A @ref Promise is connected to some `Future` and can be used to
385 * Similar to @ref std::promise
388 * // Create a promise and a future:
389 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
390 * auto future = promise->get_future();
392 * SIMIX_timer_set(date, [promise] {
394 * int value = compute_the_value();
396 * throw std::logic_error("Bad value");
397 * // Whenever the operation is completed, we set the value
399 * promise.set_value(value);
402 * // If an error occured, we can set an exception which
403 * // will be throwed buy future.get():
404 * promise.set_exception(std::current_exception());
408 * // Return the future to the caller:
415 Promise() : state_(std::make_shared<FutureState<T>>()) {}
416 Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
419 Promise(Promise&) = delete;
420 Promise& operator=(Promise&) = delete;
421 Promise(Promise&& that) :
422 state_(std::move(that.state_)), future_get_(that.future_set)
424 that.future_get_ = false;
427 Promise& operator=(Promise&& that)
429 this->state_ = std::move(that.state_);
430 this->future_get_ = that.future_get_;
431 that.future_get_ = false;
434 Future<T> get_future()
436 if (state_ == nullptr)
437 throw std::future_error(std::future_errc::no_state);
439 throw std::future_error(std::future_errc::future_already_retrieved);
441 return Future<T>(state_);
443 void set_value(T value)
445 if (state_ == nullptr)
446 throw std::future_error(std::future_errc::no_state);
447 state_->set_value(std::move(value));
449 void set_exception(std::exception_ptr exception)
451 if (state_ == nullptr)
452 throw std::future_error(std::future_errc::no_state);
453 state_->set_exception(std::move(exception));
457 if (state_ && state_->get_status() == FutureStatus::not_ready)
458 state_->set_exception(std::make_exception_ptr(
459 std::future_error(std::future_errc::broken_promise)));
463 std::shared_ptr<FutureState<T>> state_;
464 bool future_get_ = false;
468 class Promise<void> {
470 Promise() : state_(std::make_shared<FutureState<void>>()) {}
471 Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
474 if (state_ && state_->get_status() == FutureStatus::not_ready)
475 state_->set_exception(std::make_exception_ptr(
476 std::future_error(std::future_errc::broken_promise)));
480 Promise(Promise&) = delete;
481 Promise& operator=(Promise&) = delete;
482 Promise(Promise&& that) :
483 state_(std::move(that.state_)), future_get_(that.future_get_)
485 that.future_get_ = false;
487 Promise& operator=(Promise&& that)
489 this->state_ = std::move(that.state_);
490 this->future_get_ = that.future_get_;
491 that.future_get_ = false;
495 Future<void> get_future()
497 if (state_ == nullptr)
498 throw std::future_error(std::future_errc::no_state);
500 throw std::future_error(std::future_errc::future_already_retrieved);
502 return Future<void>(state_);
506 if (state_ == nullptr)
507 throw std::future_error(std::future_errc::no_state);
510 void set_exception(std::exception_ptr exception)
512 if (state_ == nullptr)
513 throw std::future_error(std::future_errc::no_state);
514 state_->set_exception(std::move(exception));
518 std::shared_ptr<FutureState<void>> state_;
519 bool future_get_ = false;