Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove useless declaration of default destructor.
[simgrid.git] / include / simgrid / kernel / future.hpp
1 /* Copyright (c) 2016-2021. The SimGrid Team.
2  * All rights reserved.                                                     */
3
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. */
6
7 #ifndef SIMGRID_KERNEL_FUTURE_HPP
8 #define SIMGRID_KERNEL_FUTURE_HPP
9
10 #include <functional>
11 #include <future>
12 #include <memory>
13 #include <utility>
14 #include <type_traits>
15
16 #include <boost/optional.hpp>
17
18 #include <xbt/base.h>
19 #include <xbt/functional.hpp>
20 #include <xbt/promise.hpp>
21
22 namespace simgrid {
23 namespace kernel {
24
25 // There are the public classes:
26 template<class T> class Future;
27 template<class T> class Promise;
28
29 // Those are implementation details:
30 enum class FutureStatus;
31 template<class T> class FutureState;
32
33 enum class FutureStatus {
34   not_ready,
35   ready,
36   done,
37 };
38
39 template<class T>
40 struct is_future : std::false_type {};
41 template<class T>
42 struct is_future<Future<T>> : std::true_type {};
43
44 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
45 class FutureStateBase {
46 public:
47   // No copy/move:
48   FutureStateBase(FutureStateBase const&) = delete;
49   FutureStateBase& operator=(FutureStateBase const&) = delete;
50
51   XBT_PUBLIC void schedule(simgrid::xbt::Task<void()>&& job) const;
52
53   void set_exception(std::exception_ptr exception)
54   {
55     xbt_assert(exception_ == nullptr);
56     if (status_ != FutureStatus::not_ready)
57       throw std::future_error(std::future_errc::promise_already_satisfied);
58     exception_ = std::move(exception);
59     this->set_ready();
60   }
61
62   void set_continuation(simgrid::xbt::Task<void()>&& continuation)
63   {
64     xbt_assert(not continuation_);
65     switch (status_) {
66     case FutureStatus::done:
67       // This is not supposed to happen if continuation is set
68       // via the Promise:
69       xbt_die("Set continuation on finished future");
70       break;
71     case FutureStatus::ready:
72       // The future is ready, execute the continuation directly.
73       // We might execute it from the event loop instead:
74       schedule(std::move(continuation));
75       break;
76     case FutureStatus::not_ready:
77       // The future is not ready so we must keep the continuation for
78       // executing it later:
79       continuation_ = std::move(continuation);
80       break;
81     default:
82       DIE_IMPOSSIBLE;
83     }
84   }
85
86   FutureStatus get_status() const
87   {
88     return status_;
89   }
90
91   bool is_ready() const
92   {
93     return status_ == FutureStatus::ready;
94   }
95
96 protected:
97   FutureStateBase() = default;
98   ~FutureStateBase() = default;
99
100   /** Set the future as ready and trigger the continuation */
101   void set_ready()
102   {
103     status_ = FutureStatus::ready;
104     if (continuation_) {
105       // We unregister the continuation before executing it.
106       // We need to do this because the current implementation of the
107       // continuation has a shared_ptr to the FutureState.
108       auto continuation = std::move(continuation_);
109       this->schedule(std::move(continuation));
110     }
111   }
112
113   /** Set the future as done and raise an exception if any
114    *
115    *  This does half the job of `.get()`.
116    **/
117   void resolve()
118   {
119     if (status_ != FutureStatus::ready)
120       xbt_die("Deadlock: this future is not ready");
121     status_ = FutureStatus::done;
122     if (exception_) {
123       std::exception_ptr exception = std::move(exception_);
124       exception_ = nullptr;
125       std::rethrow_exception(std::move(exception));
126     }
127   }
128
129 private:
130   FutureStatus status_ = FutureStatus::not_ready;
131   std::exception_ptr exception_;
132   simgrid::xbt::Task<void()> continuation_;
133 };
134
135 /** Shared state for future and promises
136  *
137  *  You are not expected to use them directly but to create them
138  *  implicitly through a @ref simgrid::kernel::Promise.
139  *  Alternatively kernel operations could inherit or contain FutureState
140  *  if they are managed with std::shared_ptr.
141  **/
142 template<class T>
143 class FutureState : public FutureStateBase {
144 public:
145   void set_value(T value)
146   {
147     if (this->get_status() != FutureStatus::not_ready)
148       throw std::future_error(std::future_errc::promise_already_satisfied);
149     value_ = std::move(value);
150     this->set_ready();
151   }
152
153   T get()
154   {
155     this->resolve();
156     xbt_assert(this->value_);
157     auto result = std::move(this->value_.get());
158     this->value_ = boost::optional<T>();
159     return result;
160   }
161
162 private:
163   boost::optional<T> value_;
164 };
165
166 template<class T>
167 class FutureState<T&> : public FutureStateBase {
168 public:
169   void set_value(T& value)
170   {
171     if (this->get_status() != FutureStatus::not_ready)
172       throw std::future_error(std::future_errc::promise_already_satisfied);
173     value_ = &value;
174     this->set_ready();
175   }
176
177   T& get()
178   {
179     this->resolve();
180     xbt_assert(this->value_);
181     T* result = value_;
182     value_ = nullptr;
183     return *result;
184   }
185
186 private:
187   T* value_ = nullptr;
188 };
189
190 template<>
191 class FutureState<void> : public FutureStateBase {
192 public:
193   void set_value()
194   {
195     if (this->get_status() != FutureStatus::not_ready)
196       throw std::future_error(std::future_errc::promise_already_satisfied);
197     this->set_ready();
198   }
199
200   void get()
201   {
202     this->resolve();
203   }
204 };
205
206 template <class T> void bind_promise(Promise<T>&& promise, Future<T> future)
207 {
208   class PromiseBinder {
209   public:
210     explicit PromiseBinder(Promise<T>&& promise) : promise_(std::move(promise)) {}
211     void operator()(Future<T> future) { simgrid::xbt::set_promise(promise_, future); }
212
213   private:
214     Promise<T> promise_;
215   };
216   future.then_(PromiseBinder(std::move(promise)));
217 }
218
219 template <class T> Future<T> unwrap_future(Future<Future<T>> future);
220
221 /** Result of some (probably) asynchronous operation in the SimGrid kernel
222  *
223  * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
224  * abstraction for asynchronous stuff happening in the SimGrid kernel. They
225  * are based on C++1z futures.
226  *
227  * The future represents a value which will be available at some point when this
228  * asynchronous operation is finished. Alternatively, if this operations fails,
229  * the result of the operation might be an exception.
230  *
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.
235  *
236  *  Example of the API (`simgrid::kernel::createProcess` does not exist):
237  *  <pre>
238  *  // Create a new process using the Worker code, this process returns
239  *  // a std::string:
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
246  *    // available:
247  *    try {
248  *      // Try to get value, this might throw an exception if the operation
249  *      // failed (such as an exception thrown by the worker process):
250  *      std::string value = result.get();
251  *      XBT_INFO("Value: %s", value.c_str());
252  *    }
253  *    catch(std::exception& e) {
254  *      // This is an exception from the asynchronous operation:
255  *      XBT_INFO("Error: %e", e.what());
256  *    }
257  *  );
258  *  </pre>
259  *
260  *  This is based on C++1z std::future but with some differences:
261  *
262  *  * there is no thread synchronization (atomic, mutex, condition variable,
263  *    etc.) because everything happens in the SimGrid event loop;
264  *
265  *  * it is purely asynchronous, you are expected to use `.then()`;
266  *
267  *  * inside the `.then()`, `.get()` can be used;
268  *
269  *  * `.get()` can only be used when `.is_ready()` (as everything happens in
270  *     a single-thread, the future would be guaranteed to deadlock if `.get()`
271  *     is called when the future is not ready);
272  *
273  *  * there is no future chaining support for now (`.then().then()`);
274  *
275  *  * there is no sharing (`shared_future`) for now.
276  */
277 template<class T>
278 class Future {
279 public:
280   Future() = default;
281   explicit Future(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
282
283   // Move type:
284   Future(Future&) = delete;
285   Future& operator=(const Future&) = delete;
286   Future(Future&&) noexcept        = default;
287   Future& operator=(Future&&) noexcept = default;
288
289   /** Whether the future is valid:.
290    *
291    *  A future which as been used (`.then` of `.get`) becomes invalid.
292    *
293    *  We can use `.then` on a valid future.
294    */
295   bool valid() const
296   {
297     return state_ != nullptr;
298   }
299
300   /** Whether the future is ready
301    *
302    *  A future is ready when it has an associated value or exception.
303    *
304    *  We can use `.get()` on ready futures.
305    **/
306   bool is_ready() const
307   {
308     return state_ != nullptr && state_->is_ready();
309   }
310
311   /** Attach a continuation to this future
312    *
313    *  This is like .then() but avoid the creation of a new future.
314    */
315   template<class F>
316   void then_(F continuation)
317   {
318     if (state_ == nullptr)
319       throw std::future_error(std::future_errc::no_state);
320     // Give shared-ownership to the continuation:
321     auto state = std::move(state_);
322     state->set_continuation(simgrid::xbt::make_task(std::move(continuation), state));
323   }
324
325   /** Attach a continuation to this future
326    *
327    *  This version never does future unwrapping.
328    */
329   template <class F> auto then_no_unwrap(F continuation) -> Future<decltype(continuation(std::move(*this)))>
330   {
331     using R = decltype(continuation(std::move(*this)));
332     if (state_ == nullptr)
333       throw std::future_error(std::future_errc::no_state);
334     auto state = std::move(state_);
335     // Create a new future...
336     Promise<R> promise;
337     Future<R> future = promise.get_future();
338     // ...and when the current future is ready...
339     state->set_continuation(simgrid::xbt::make_task(
340         [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
341           // ...set the new future value by running the continuation.
342           Future<T> future(std::move(state));
343           simgrid::xbt::fulfill_promise(promise, [&continuation, &future] { return continuation(std::move(future)); });
344         },
345         std::move(promise), state, std::move(continuation)));
346     return future;
347   }
348
349   /** Attach a continuation to this future
350    *
351    *  The future must be valid in order to make this call.
352    *  The continuation is executed when the future becomes ready.
353    *  The future becomes invalid after this call.
354    *
355    * @param continuation This function is called with a ready future
356    *                     the future is ready
357    * @exception std::future_error no state is associated with the future
358    */
359   template <class F>
360   auto then(F continuation) -> typename std::enable_if_t<not is_future<decltype(continuation(std::move(*this)))>::value,
361                                                          Future<decltype(continuation(std::move(*this)))>>
362   {
363     return this->then_no_unwrap(std::move(continuation));
364   }
365
366   /** Attach a continuation to this future (future chaining) */
367   template <class F>
368   auto then(F continuation) -> typename std::enable_if_t<is_future<decltype(continuation(std::move(*this)))>::value,
369                                                          decltype(continuation(std::move(*this)))>
370   {
371     return unwrap_future(this->then_no_unwrap(std::move(continuation)));
372   }
373
374   /** Get the value from the future
375    *
376    *  The future must be valid and ready in order to make this call.
377    *  std::future blocks when the future is not ready but we are
378    *  completely single-threaded so blocking would be a deadlock.
379    *  After the call, the future becomes invalid.
380    *
381    *  @return                      value of the future
382    *  @exception any               Exception from the future
383    *  @exception std::future_error no state is associated with the future
384    */
385   T get()
386   {
387     if (state_ == nullptr)
388       throw std::future_error(std::future_errc::no_state);
389     std::shared_ptr<FutureState<T>> state = std::move(state_);
390     return state->get();
391   }
392
393 private:
394   std::shared_ptr<FutureState<T>> state_;
395 };
396
397 template <class T> Future<T> unwrap_future(Future<Future<T>> future)
398 {
399   Promise<T> promise;
400   Future<T> result = promise.get_future();
401   bind_promise(std::move(promise), std::move(future));
402   return result;
403 }
404
405 /** Producer side of a @ref simgrid::kernel::Future
406  *
407  *  A @ref Promise is connected to some `Future` and can be used to
408  *  set its result.
409  *
410  *  Similar to std::promise
411  *
412  *  <code>
413  *  // Create a promise and a future:
414  *  auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
415  *  auto future = promise->get_future();
416  *
417  *  simgrid::simix::Timer::set(date, [promise] {
418  *    try {
419  *      int value = compute_the_value();
420  *      if (value < 0)
421  *        throw std::logic_error("Bad value");
422  *      // Whenever the operation is completed, we set the value
423  *      // for the future:
424  *      promise.set_value(value);
425  *    }
426  *    catch (...) {
427  *      // If an error occurred, we can set an exception which
428  *      // will be thrown by future.get():
429  *      promise.set_exception(std::current_exception());
430  *    }
431  *  });
432  *
433  *  // Return the future to the caller:
434  *  return future;
435  *  </code>
436  **/
437 template<class T>
438 class Promise {
439 public:
440   Promise() = default;
441   explicit Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
442
443   // Move type
444   Promise(Promise const&) = delete;
445   Promise& operator=(Promise const&) = delete;
446   Promise(Promise&& that) noexcept : state_(std::move(that.state_)) { std::swap(future_get_, that.future_get_); }
447
448   Promise& operator=(Promise&& that) noexcept
449   {
450     this->state_ = std::move(that.state_);
451     this->future_get_ = that.future_get_;
452     that.future_get_ = false;
453     return *this;
454   }
455   Future<T> get_future()
456   {
457     if (state_ == nullptr)
458       throw std::future_error(std::future_errc::no_state);
459     if (future_get_)
460       throw std::future_error(std::future_errc::future_already_retrieved);
461     future_get_ = true;
462     return Future<T>(state_);
463   }
464   void set_value(T value)
465   {
466     if (state_ == nullptr)
467       throw std::future_error(std::future_errc::no_state);
468     state_->set_value(std::move(value));
469   }
470   void set_exception(std::exception_ptr exception)
471   {
472     if (state_ == nullptr)
473       throw std::future_error(std::future_errc::no_state);
474     state_->set_exception(std::move(exception));
475   }
476   ~Promise()
477   {
478     if (state_ && state_->get_status() == FutureStatus::not_ready)
479       state_->set_exception(std::make_exception_ptr(
480         std::future_error(std::future_errc::broken_promise)));
481   }
482
483 private:
484   std::shared_ptr<FutureState<T>> state_ = std::make_shared<FutureState<T>>();
485   bool future_get_ = false;
486 };
487
488 template<>
489 class Promise<void> {
490 public:
491   Promise() = default;
492   explicit Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
493   ~Promise()
494   {
495     if (state_ && state_->get_status() == FutureStatus::not_ready)
496       state_->set_exception(std::make_exception_ptr(
497         std::future_error(std::future_errc::broken_promise)));
498   }
499
500   // Move type
501   Promise(Promise const&) = delete;
502   Promise& operator=(Promise const&) = delete;
503   Promise(Promise&& that) noexcept : state_(std::move(that.state_)) { std::swap(future_get_, that.future_get_); }
504   Promise& operator=(Promise&& that) noexcept
505   {
506     this->state_ = std::move(that.state_);
507     this->future_get_ = that.future_get_;
508     that.future_get_ = false;
509     return *this;
510   }
511
512   Future<void> get_future()
513   {
514     if (state_ == nullptr)
515       throw std::future_error(std::future_errc::no_state);
516     if (future_get_)
517       throw std::future_error(std::future_errc::future_already_retrieved);
518     future_get_ = true;
519     return Future<void>(state_);
520   }
521   void set_value() const
522   {
523     if (state_ == nullptr)
524       throw std::future_error(std::future_errc::no_state);
525     state_->set_value();
526   }
527   void set_exception(std::exception_ptr exception) const
528   {
529     if (state_ == nullptr)
530       throw std::future_error(std::future_errc::no_state);
531     state_->set_exception(std::move(exception));
532   }
533
534 private:
535   std::shared_ptr<FutureState<void>> state_ = std::make_shared<FutureState<void>>();
536   bool future_get_ = false;
537 };
538
539 }
540 }
541
542 #endif