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);
76 FutureStatus get_status() const
83 return status_ == FutureStatus::ready;
88 ~FutureStateBase() {};
90 /** Set the future as ready and trigger the continuation */
93 status_ = FutureStatus::ready;
95 // We unregister the continuation before executing it.
96 // We need to do this becase the current implementation of the
97 // continuation has a shared_ptr to the FutureState.
98 auto continuation = std::move(continuation_);
103 /** Set the future as done and raise an exception if any
105 * This does half the job of `.get()`.
109 if (status_ != FutureStatus::ready)
110 xbt_die("Deadlock: this future is not ready");
111 status_ = FutureStatus::done;
113 std::exception_ptr exception = std::move(exception_);
114 std::rethrow_exception(std::move(exception));
119 FutureStatus status_ = FutureStatus::not_ready;
120 std::exception_ptr exception_;
121 simgrid::xbt::Task<void()> continuation_;
124 /** Shared state for future and promises
126 * You are not expected to use them directly but to create them
127 * implicitely through a @ref simgrid::kernel::Promise.
128 * Alternatively kernel operations could inherit or contain FutureState
129 * if they are managed with @ref std::shared_ptr.
132 class FutureState : public FutureStateBase {
135 void set_value(T value)
137 if (this->get_status() != FutureStatus::not_ready)
138 throw std::future_error(std::future_errc::promise_already_satisfied);
139 value_ = std::move(value);
146 xbt_assert(this->value_);
147 auto result = std::move(this->value_.get());
148 this->value_ = boost::optional<T>();
149 return std::move(result);
153 boost::optional<T> value_;
157 class FutureState<T&> : public FutureStateBase {
159 void set_value(T& value)
161 if (this->get_status() != FutureStatus::not_ready)
162 throw std::future_error(std::future_errc::promise_already_satisfied);
170 xbt_assert(this->value_);
181 class FutureState<void> : public FutureStateBase {
185 if (this->get_status() != FutureStatus::not_ready)
186 throw std::future_error(std::future_errc::promise_already_satisfied);
196 /** Result of some (probably) asynchronous operation in the SimGrid kernel
198 * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
199 * abstration for asynchronous stuff happening in the SimGrid kernel. They
200 * are based on C++1z futures.
202 * The future represents a value which will be available at some point when this
203 * asynchronous operaiont is finished. Alternatively, if this operations fails,
204 * the result of the operation might be an exception.
206 * As the operation is possibly no terminated yet, we cannot get the result
207 * yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
208 * it. However, we can attach some code/callback/continuation which will be
209 * executed when the operation terminates.
211 * Example of the API (`simgrid::kernel::createProcess` does not exist):
213 * // Create a new process using the Worker code, this process returns
215 * simgrid::kernel::Future<std::string> future =
216 * simgrid::kernel::createProcess("worker42", host, Worker(42));
217 * // At this point, we just created the process so the result is not available.
218 * // However, we can attach some work do be done with this result:
219 * future.then([](simgrid::kernel::Future<std::string> result) {
220 * // This code is called when the operation is completed so the result is
223 * // Try to get value, this might throw an exception if the operation
224 * // failed (such as an exception throwed by the worker process):
225 * std::string value = result.get();
226 * XBT_INFO("Value: %s", value.c_str());
228 * catch(std::exception& e) {
229 * // This is an exception from the asynchronous operation:
230 * XBT_INFO("Error: %e", e.what());
235 * This is based on C++1z @ref std::future but with some differences:
237 * * there is no thread synchronization (atomic, mutex, condition variable,
238 * etc.) because everything happens in the SimGrid event loop;
240 * * it is purely asynchronous, you are expected to use `.then()`;
242 * * inside the `.then()`, `.get()` can be used;
244 * * `.get()` can only be used when `.is_ready()` (as everything happens in
245 * a single-thread, the future would be guaranted to deadlock if `.get()`
246 * is called when the future is not ready);
248 * * there is no future chaining support for now (`.then().then()`);
250 * * there is no sharing (`shared_future`) for now.
256 Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
259 Future(Future&) = delete;
260 Future& operator=(Future&) = delete;
261 Future(Future&& that) : state_(std::move(that.state_)) {}
262 Future& operator=(Future&& that)
264 state_ = std::move(that.state_);
268 /** Whether the future is valid:.
270 * A future which as been used (`.then` of `.get`) becomes invalid.
272 * We can use `.then` on a valid future.
276 return state_ != nullptr;
279 /** Whether the future is ready
281 * A future is ready when it has an associated value or exception.
283 * We can use `.get()` on ready futures.
285 bool is_ready() const
287 return state_ != nullptr && state_->is_ready();
290 /** Attach a continuation to this future
292 * The future must be valid in order to make this call.
293 * The continuation is executed when the future becomes ready.
294 * The future becomes invalid after this call.
296 * We don't support future chaining for now (`.then().then()`).
298 * @param continuation This function is called with a ready future
299 * the future is ready
300 * @exception std::future_error no state is associated with the future
303 void then(F continuation)
305 if (state_ == nullptr)
306 throw std::future_error(std::future_errc::no_state);
307 // Give shared-ownership to the continuation:
308 auto state = std::move(state_);
309 state->set_continuation(simgrid::xbt::makeTask(
310 std::move(continuation), state));
313 /** Get the value from the future
315 * This is expected to be called
317 * The future must be valid and ready in order to make this call.
318 * @ref std::future blocks when the future is not ready but we are
319 * completely single-threaded so blocking would be a deadlock.
320 * After the call, the future becomes invalid.
322 * @return value of the future
323 * @exception any Exception from the future
324 * @exception std::future_error no state is associated with the future
328 if (state_ == nullptr)
329 throw std::future_error(std::future_errc::no_state);
330 std::shared_ptr<FutureState<T>> state = std::move(state_);
335 std::shared_ptr<FutureState<T>> state_;
338 /** Producer side of a @simgrid::kernel::Future
340 * A @ref Promise is connected to some `Future` and can be used to
343 * Similar to @ref std::promise
346 * // Create a promise and a future:
347 * auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
348 * auto future = promise->get_future();
350 * SIMIX_timer_set(date, [promise] {
352 * int value = compute_the_value();
354 * throw std::logic_error("Bad value");
355 * // Whenever the operation is completed, we set the value
357 * promise.set_value(value);
360 * // If an error occured, we can set an exception which
361 * // will be throwed buy future.get():
362 * promise.set_exception(std::current_exception());
366 * // Return the future to the caller:
373 Promise() : state_(std::make_shared<FutureState<T>>()) {}
374 Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
377 Promise(Promise&) = delete;
378 Promise& operator=(Promise&) = delete;
379 Promise(Promise&& that) :
380 state_(std::move(that.state_)), future_get_(that.future_set)
382 that.future_get_ = false;
385 Promise& operator=(Promise&& that)
387 this->state_ = std::move(that.state_);
388 this->future_get_ = that.future_get_;
389 that.future_get_ = false;
392 Future<T> get_future()
394 if (state_ == nullptr)
395 throw std::future_error(std::future_errc::no_state);
397 throw std::future_error(std::future_errc::future_already_retrieved);
399 return Future<T>(state_);
401 void set_value(T value)
403 if (state_ == nullptr)
404 throw std::future_error(std::future_errc::no_state);
405 state_->set_value(std::move(value));
407 void set_exception(std::exception_ptr exception)
409 if (state_ == nullptr)
410 throw std::future_error(std::future_errc::no_state);
411 state_->set_exception(std::move(exception));
415 if (state_ && state_->get_status() == FutureStatus::not_ready)
416 state_->set_exception(std::make_exception_ptr(
417 std::future_error(std::future_errc::broken_promise)));
421 std::shared_ptr<FutureState<T>> state_;
422 bool future_get_ = false;
426 class Promise<void> {
428 Promise() : state_(std::make_shared<FutureState<void>>()) {}
429 Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
432 if (state_ && state_->get_status() == FutureStatus::not_ready)
433 state_->set_exception(std::make_exception_ptr(
434 std::future_error(std::future_errc::broken_promise)));
438 Promise(Promise&) = delete;
439 Promise& operator=(Promise&) = delete;
440 Promise(Promise&& that) :
441 state_(std::move(that.state_)), future_get_(that.future_get_)
443 that.future_get_ = false;
445 Promise& operator=(Promise&& that)
447 this->state_ = std::move(that.state_);
448 this->future_get_ = that.future_get_;
449 that.future_get_ = false;
453 Future<void> get_future()
455 if (state_ == nullptr)
456 throw std::future_error(std::future_errc::no_state);
458 throw std::future_error(std::future_errc::future_already_retrieved);
460 return Future<void>(state_);
464 if (state_ == nullptr)
465 throw std::future_error(std::future_errc::no_state);
468 void set_exception(std::exception_ptr exception)
470 if (state_ == nullptr)
471 throw std::future_error(std::future_errc::no_state);
472 state_->set_exception(std::move(exception));
476 std::shared_ptr<FutureState<void>> state_;
477 bool future_get_ = false;