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>
13 #include <xbt/functional.hpp>
19 #include <type_traits>
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 {
38 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
39 class FutureStateBase {
42 FutureStateBase(FutureStateBase const&) = delete;
43 FutureStateBase& operator=(FutureStateBase const&) = delete;
45 void set_exception(std::exception_ptr exception)
47 xbt_assert(exception_ == nullptr);
48 if (status_ != FutureStatus::not_ready)
49 throw std::future_error(std::future_errc::promise_already_satisfied);
50 exception_ = std::move(exception);
54 void set_continuation(simgrid::xbt::Task<void()> continuation)
56 xbt_assert(!continuation_);
58 case FutureStatus::done:
59 // This is not supposed to happen if continuation is set
61 xbt_die("Set continuation on finished future");
63 case FutureStatus::ready:
64 // The future is ready, execute the continuation directly.
65 // We might execute it from the event loop instead:
68 case FutureStatus::not_ready:
69 // The future is not ready so we mast keep the continuation for
70 // executing it later:
71 continuation_ = std::move(continuation);
78 FutureStatus get_status() const
85 return status_ == FutureStatus::ready;
89 FutureStateBase() = default;
90 ~FutureStateBase() = default;
92 /** Set the future as ready and trigger the continuation */
95 status_ = FutureStatus::ready;
97 // We unregister the continuation before executing it.
98 // We need to do this becase the current implementation of the
99 // continuation has a shared_ptr to the FutureState.
100 auto continuation = std::move(continuation_);
105 /** Set the future as done and raise an exception if any
107 * This does half the job of `.get()`.
111 if (status_ != FutureStatus::ready)
112 xbt_die("Deadlock: this future is not ready");
113 status_ = FutureStatus::done;
115 std::exception_ptr exception = std::move(exception_);
116 std::rethrow_exception(std::move(exception));
121 FutureStatus status_ = FutureStatus::not_ready;
122 std::exception_ptr exception_;
123 simgrid::xbt::Task<void()> continuation_;
126 /** Shared state for future and promises
128 * You are not expected to use them directly but to create them
129 * implicitely through a @ref simgrid::kernel::Promise.
130 * Alternatively kernel operations could inherit or contain FutureState
131 * if they are managed with @ref std::shared_ptr.
134 class FutureState : public FutureStateBase {
137 void set_value(T value)
139 if (this->get_status() != FutureStatus::not_ready)
140 throw std::future_error(std::future_errc::promise_already_satisfied);
141 value_ = std::move(value);
148 xbt_assert(this->value_);
149 auto result = std::move(this->value_.get());
150 this->value_ = boost::optional<T>();
151 return std::move(result);
155 boost::optional<T> value_;
159 class FutureState<T&> : public FutureStateBase {
161 void set_value(T& value)
163 if (this->get_status() != FutureStatus::not_ready)
164 throw std::future_error(std::future_errc::promise_already_satisfied);
172 xbt_assert(this->value_);
183 class FutureState<void> : public FutureStateBase {
187 if (this->get_status() != FutureStatus::not_ready)
188 throw std::future_error(std::future_errc::promise_already_satisfied);
198 /** Result of some (probably) asynchronous operation in the SimGrid kernel
200 * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
201 * abstration for asynchronous stuff happening in the SimGrid kernel. They
202 * are based on C++1z futures.
204 * The future represents a value which will be available at some point when this
205 * asynchronous operaiont is finished. Alternatively, if this operations fails,
206 * the result of the operation might be an exception.
208 * As the operation is possibly no terminated yet, we cannot get the result
209 * yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
210 * it. However, we can attach some code/callback/continuation which will be
211 * executed when the operation terminates.
213 * Example of the API (`simgrid::kernel::createProcess` does not exist):
215 * // Create a new process using the Worker code, this process returns
217 * simgrid::kernel::Future<std::string> future =
218 * simgrid::kernel::createProcess("worker42", host, Worker(42));
219 * // At this point, we just created the process so the result is not available.
220 * // However, we can attach some work do be done with this result:
221 * future.then([](simgrid::kernel::Future<std::string> result) {
222 * // This code is called when the operation is completed so the result is
225 * // Try to get value, this might throw an exception if the operation
226 * // failed (such as an exception throwed by the worker process):
227 * std::string value = result.get();
228 * XBT_INFO("Value: %s", value.c_str());
230 * catch(std::exception& e) {
231 * // This is an exception from the asynchronous operation:
232 * XBT_INFO("Error: %e", e.what());
237 * This is based on C++1z @ref std::future but with some differences:
239 * * there is no thread synchronization (atomic, mutex, condition variable,
240 * etc.) because everything happens in the SimGrid event loop;
242 * * it is purely asynchronous, you are expected to use `.then()`;
244 * * inside the `.then()`, `.get()` can be used;
246 * * `.get()` can only be used when `.is_ready()` (as everything happens in
247 * a single-thread, the future would be guaranted to deadlock if `.get()`
248 * is called when the future is not ready);
250 * * there is no future chaining support for now (`.then().then()`);
252 * * there is no sharing (`shared_future`) for now.
258 Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
261 Future(Future&) = delete;
262 Future& operator=(Future&) = delete;
263 Future(Future&& that) : state_(std::move(that.state_)) {}
264 Future& operator=(Future&& that)
266 state_ = std::move(that.state_);
270 /** Whether the future is valid:.
272 * A future which as been used (`.then` of `.get`) becomes invalid.
274 * We can use `.then` on a valid future.
278 return state_ != nullptr;
281 /** Whether the future is ready
283 * A future is ready when it has an associated value or exception.
285 * We can use `.get()` on ready futures.
287 bool is_ready() const
289 return state_ != nullptr && state_->is_ready();
292 /** Attach a continuation to this future
294 * The future must be valid in order to make this call.
295 * The continuation is executed when the future becomes ready.
296 * The future becomes invalid after this call.
298 * We don't support future chaining for now (`.then().then()`).
300 * @param continuation This function is called with a ready future
301 * the future is ready
302 * @exception std::future_error no state is associated with the future
305 void then(F continuation)
307 if (state_ == nullptr)
308 throw std::future_error(std::future_errc::no_state);
309 // Give shared-ownership to the continuation:
310 auto state = std::move(state_);
311 state->set_continuation(simgrid::xbt::makeTask(
312 std::move(continuation), state));
315 /** Get the value from the future
317 * This is expected to be called
319 * The future must be valid and ready in order to make this call.
320 * @ref std::future blocks when the future is not ready but we are
321 * completely single-threaded so blocking would be a deadlock.
322 * After the call, the future becomes invalid.
324 * @return value of the future
325 * @exception any Exception from the future
326 * @exception std::future_error no state is associated with the future
330 if (state_ == nullptr)
331 throw std::future_error(std::future_errc::no_state);
332 std::shared_ptr<FutureState<T>> state = std::move(state_);
337 std::shared_ptr<FutureState<T>> state_;
340 /** Producer side of a @simgrid::kernel::Future
342 * A @ref Promise is connected to some `Future` and can be used to
345 * Similar to @ref std::promise
348 * // Create a promise and a future:
349 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
350 * auto future = promise->get_future();
352 * SIMIX_timer_set(date, [promise] {
354 * int value = compute_the_value();
356 * throw std::logic_error("Bad value");
357 * // Whenever the operation is completed, we set the value
359 * promise.set_value(value);
362 * // If an error occured, we can set an exception which
363 * // will be throwed buy future.get():
364 * promise.set_exception(std::current_exception());
368 * // Return the future to the caller:
375 Promise() : state_(std::make_shared<FutureState<T>>()) {}
376 Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
379 Promise(Promise&) = delete;
380 Promise& operator=(Promise&) = delete;
381 Promise(Promise&& that) :
382 state_(std::move(that.state_)), future_get_(that.future_set)
384 that.future_get_ = false;
387 Promise& operator=(Promise&& that)
389 this->state_ = std::move(that.state_);
390 this->future_get_ = that.future_get_;
391 that.future_get_ = false;
394 Future<T> get_future()
396 if (state_ == nullptr)
397 throw std::future_error(std::future_errc::no_state);
399 throw std::future_error(std::future_errc::future_already_retrieved);
401 return Future<T>(state_);
403 void set_value(T value)
405 if (state_ == nullptr)
406 throw std::future_error(std::future_errc::no_state);
407 state_->set_value(std::move(value));
409 void set_exception(std::exception_ptr exception)
411 if (state_ == nullptr)
412 throw std::future_error(std::future_errc::no_state);
413 state_->set_exception(std::move(exception));
417 if (state_ && state_->get_status() == FutureStatus::not_ready)
418 state_->set_exception(std::make_exception_ptr(
419 std::future_error(std::future_errc::broken_promise)));
423 std::shared_ptr<FutureState<T>> state_;
424 bool future_get_ = false;
428 class Promise<void> {
430 Promise() : state_(std::make_shared<FutureState<void>>()) {}
431 Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
434 if (state_ && state_->get_status() == FutureStatus::not_ready)
435 state_->set_exception(std::make_exception_ptr(
436 std::future_error(std::future_errc::broken_promise)));
440 Promise(Promise&) = delete;
441 Promise& operator=(Promise&) = delete;
442 Promise(Promise&& that) :
443 state_(std::move(that.state_)), future_get_(that.future_get_)
445 that.future_get_ = false;
447 Promise& operator=(Promise&& that)
449 this->state_ = std::move(that.state_);
450 this->future_get_ = that.future_get_;
451 that.future_get_ = false;
455 Future<void> get_future()
457 if (state_ == nullptr)
458 throw std::future_error(std::future_errc::no_state);
460 throw std::future_error(std::future_errc::future_already_retrieved);
462 return Future<void>(state_);
466 if (state_ == nullptr)
467 throw std::future_error(std::future_errc::no_state);
470 void set_exception(std::exception_ptr exception)
472 if (state_ == nullptr)
473 throw std::future_error(std::future_errc::no_state);
474 state_->set_exception(std::move(exception));
478 std::shared_ptr<FutureState<void>> state_;
479 bool future_get_ = false;