Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
5c11dbb056c08c4755fd30b8e7748594a0986116
[simgrid.git] / include / simgrid / kernel / future.hpp
1 /* Copyright (c) 2016. 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
21 namespace simgrid {
22 namespace kernel {
23
24 // There are the public classes:
25 template<class T> class Future;
26 template<class T> class Promise;
27
28 // Those are implementation details:
29 enum class FutureStatus;
30 template<class T> class FutureState;
31
32 enum class FutureStatus {
33   not_ready,
34   ready,
35   done,
36 };
37
38 template<class T>
39 struct is_future : public std::integral_constant<bool, false> {};
40 template<class T>
41 struct is_future<Future<T>> : public std::integral_constant<bool, true> {};
42
43 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
44 class FutureStateBase {
45 public:
46   // No copy/move:
47   FutureStateBase(FutureStateBase const&) = delete;
48   FutureStateBase& operator=(FutureStateBase const&) = delete;
49
50   void set_exception(std::exception_ptr exception)
51   {
52     xbt_assert(exception_ == nullptr);
53     if (status_ != FutureStatus::not_ready)
54       throw std::future_error(std::future_errc::promise_already_satisfied);
55     exception_ = std::move(exception);
56     this->set_ready();
57   }
58
59   void set_continuation(simgrid::xbt::Task<void()> continuation)
60   {
61     xbt_assert(!continuation_);
62     switch (status_) {
63     case FutureStatus::done:
64       // This is not supposed to happen if continuation is set
65       // via the Promise:
66       xbt_die("Set continuation on finished future");
67       break;
68     case FutureStatus::ready:
69       // The future is ready, execute the continuation directly.
70       // We might execute it from the event loop instead:
71       continuation();
72       break;
73     case FutureStatus::not_ready:
74       // The future is not ready so we mast keep the continuation for
75       // executing it later:
76       continuation_ = std::move(continuation);
77       break;
78     default:
79       DIE_IMPOSSIBLE;
80     }
81   }
82
83   FutureStatus get_status() const
84   {
85     return status_;
86   }
87
88   bool is_ready() const
89   {
90     return status_ == FutureStatus::ready;
91   }
92
93 protected:
94   FutureStateBase() = default;
95   ~FutureStateBase() = default;
96
97   /** Set the future as ready and trigger the continuation */
98   void set_ready()
99   {
100     status_ = FutureStatus::ready;
101     if (continuation_) {
102       // We unregister the continuation before executing it.
103       // We need to do this becase the current implementation of the
104       // continuation has a shared_ptr to the FutureState.
105       auto continuation = std::move(continuation_);
106       continuation();
107     }
108   }
109
110   /** Set the future as done and raise an exception if any
111    *
112    *  This does half the job of `.get()`.
113    **/
114   void resolve()
115   {
116     if (status_ != FutureStatus::ready)
117       xbt_die("Deadlock: this future is not ready");
118     status_ = FutureStatus::done;
119     if (exception_) {
120       std::exception_ptr exception = std::move(exception_);
121       std::rethrow_exception(std::move(exception));
122     }
123   }
124
125 private:
126   FutureStatus status_ = FutureStatus::not_ready;
127   std::exception_ptr exception_;
128   simgrid::xbt::Task<void()> continuation_;
129 };
130
131 /** Shared state for future and promises
132  *
133  *  You are not expected to use them directly but to create them
134  *  implicitely through a @ref simgrid::kernel::Promise.
135  *  Alternatively kernel operations could inherit or contain FutureState
136  *  if they are managed with @ref std::shared_ptr.
137  **/
138 template<class T>
139 class FutureState : public FutureStateBase {
140 public:
141
142   void set_value(T value)
143   {
144     if (this->get_status() != FutureStatus::not_ready)
145       throw std::future_error(std::future_errc::promise_already_satisfied);
146     value_ = std::move(value);
147     this->set_ready();
148   }
149
150   T get()
151   {
152     this->resolve();
153     xbt_assert(this->value_);
154     auto result = std::move(this->value_.get());
155     this->value_ = boost::optional<T>();
156     return std::move(result);
157   }
158
159 private:
160   boost::optional<T> value_;
161 };
162
163 template<class T>
164 class FutureState<T&> : public FutureStateBase {
165 public:
166   void set_value(T& value)
167   {
168     if (this->get_status() != FutureStatus::not_ready)
169       throw std::future_error(std::future_errc::promise_already_satisfied);
170     value_ = &value;
171     this->set_ready();
172   }
173
174   T& get()
175   {
176     this->resolve();
177     xbt_assert(this->value_);
178     T* result = value_;
179     value_ = nullptr;
180     return *value_;
181   }
182
183 private:
184   T* value_ = nullptr;
185 };
186
187 template<>
188 class FutureState<void> : public FutureStateBase {
189 public:
190   void set_value()
191   {
192     if (this->get_status() != FutureStatus::not_ready)
193       throw std::future_error(std::future_errc::promise_already_satisfied);
194     this->set_ready();
195   }
196
197   void get()
198   {
199     this->resolve();
200   }
201 };
202
203 template<class T>
204 void bindPromise(Promise<T> promise, Future<T> future)
205 {
206   struct PromiseBinder {
207   public:
208     PromiseBinder(Promise<T> promise) : promise_(std::move(promise)) {}
209     void operator()(Future<T> future)
210     {
211       simgrid::xbt::setPromise(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> unwrapFuture(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  * abstration 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 operaiont 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 throwed 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 @ref 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 guaranted 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   Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
282
283   // Move type:
284   Future(Future&) = delete;
285   Future& operator=(Future&) = delete;
286   Future(Future&& that) : state_(std::move(that.state_)) {}
287   Future& operator=(Future&& that)
288   {
289     state_ = std::move(that.state_);
290     return *this;
291   }
292
293   /** Whether the future is valid:.
294    *
295    *  A future which as been used (`.then` of `.get`) becomes invalid.
296    *
297    *  We can use `.then` on a valid future.
298    */
299   bool valid() const
300   {
301     return state_ != nullptr;
302   }
303
304   /** Whether the future is ready
305    *
306    *  A future is ready when it has an associated value or exception.
307    *
308    *  We can use `.get()` on ready futures.
309    **/
310   bool is_ready() const
311   {
312     return state_ != nullptr && state_->is_ready();
313   }
314
315   /** Attach a continuation to this future
316    *
317    *  This is like .then() but avoid the creation of a new future.
318    */
319   template<class F>
320   void then_(F continuation)
321   {
322     if (state_ == nullptr)
323       throw std::future_error(std::future_errc::no_state);
324     // Give shared-ownership to the continuation:
325     auto state = std::move(state_);
326     state->set_continuation(simgrid::xbt::makeTask(
327       std::move(continuation), state));
328   }
329
330   /** Attach a continuation to this future
331    *
332    *  This version never does future unwrapping.
333    */
334   template<class F>
335   auto thenNoUnwrap(F continuation)
336   -> Future<decltype(continuation(std::move(*this)))>
337   {
338     typedef decltype(continuation(std::move(*this))) R;
339     if (state_ == nullptr)
340       throw std::future_error(std::future_errc::no_state);
341     auto state = std::move(state_);
342     // Create a new future...
343     Promise<R> promise;
344     Future<R> future = promise.get_future();
345     // ...and when the current future is ready...
346     state->set_continuation(simgrid::xbt::makeTask(
347       [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
348         // ...set the new future value by running the continuation.
349         Future<T> future(std::move(state));
350         simgrid::xbt::fulfillPromise(promise,[&]{
351           return continuation(std::move(future));
352         });
353       },
354       std::move(promise), state, std::move(continuation)));
355     return std::move(future);
356   }
357
358   /** Attach a continuation to this future
359    *
360    *  The future must be valid in order to make this call.
361    *  The continuation is executed when the future becomes ready.
362    *  The future becomes invalid after this call.
363    *
364    * @param continuation This function is called with a ready future
365    *                     the future is ready
366    * @exception std::future_error no state is associated with the future
367    */
368   template<class F>
369   auto then(F continuation)
370   -> typename std::enable_if<
371        !is_future<decltype(continuation(std::move(*this)))>::value,
372        Future<decltype(continuation(std::move(*this)))>
373      >::type
374   {
375     return this->thenNoUnwrap(std::move(continuation));
376   }
377
378   /** Attach a continuation to this future (future chaining) */
379   template<class F>
380   auto then(F continuation)
381   -> typename std::enable_if<
382        is_future<decltype(continuation(std::move(*this)))>::value,
383        decltype(continuation(std::move(*this)))
384      >::type
385   {
386     return unwrapFuture(this->thenNoUnwap(std::move(continuation)));
387   }
388
389   /** Get the value from the future
390    *
391    *  This is expected to be called
392    *
393    *  The future must be valid and ready in order to make this call.
394    *  @ref std::future blocks when the future is not ready but we are
395    *  completely single-threaded so blocking would be a deadlock.
396    *  After the call, the future becomes invalid.
397    *
398    *  @return                      value of the future
399    *  @exception any               Exception from the future
400    *  @exception std::future_error no state is associated with the future
401    */
402   T get()
403   {
404     if (state_ == nullptr)
405       throw std::future_error(std::future_errc::no_state);
406     std::shared_ptr<FutureState<T>> state = std::move(state_);
407     return state->get();
408   }
409
410 private:
411   std::shared_ptr<FutureState<T>> state_;
412 };
413
414 template<class T>
415 Future<T> unwrapFuture(Future<Future<T>> future)
416 {
417   Promise<T> promise;
418   Future<T> result = promise.get_future();
419   bindPromise(std::move(promise), std::move(future));
420   return std::move(result);
421 }
422
423 /** Producer side of a @simgrid::kernel::Future
424  *
425  *  A @ref Promise is connected to some `Future` and can be used to
426  *  set its result.
427  *
428  *  Similar to @ref std::promise
429  *
430  *  <code>
431  *  // Create a promise and a future:
432  *  auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
433  *  auto future = promise->get_future();
434  *
435  *  SIMIX_timer_set(date, [promise] {
436  *    try {
437  *      int value = compute_the_value();
438  *      if (value < 0)
439  *        throw std::logic_error("Bad value");
440  *      // Whenever the operation is completed, we set the value
441  *      // for the future:
442  *      promise.set_value(value);
443  *    }
444  *    catch (...) {
445  *      // If an error occured, we can set an exception which
446  *      // will be throwed buy future.get():
447  *      promise.set_exception(std::current_exception());
448  *    }
449  *  });
450  *
451  *  // Return the future to the caller:
452  *  return future;
453  *  </code>
454  **/
455 template<class T>
456 class Promise {
457 public:
458   Promise() : state_(std::make_shared<FutureState<T>>()) {}
459   Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
460
461   // Move type
462   Promise(Promise const&) = delete;
463   Promise& operator=(Promise const&) = delete;
464   Promise(Promise&& that) :
465     state_(std::move(that.state_)), future_get_(that.future_get_)
466   {
467     that.future_get_ = false;
468   }
469
470   Promise& operator=(Promise&& that)
471   {
472     this->state_ = std::move(that.state_);
473     this->future_get_ = that.future_get_;
474     that.future_get_ = false;
475     return *this;
476   }
477   Future<T> get_future()
478   {
479     if (state_ == nullptr)
480       throw std::future_error(std::future_errc::no_state);
481     if (future_get_)
482       throw std::future_error(std::future_errc::future_already_retrieved);
483     future_get_ = true;
484     return Future<T>(state_);
485   }
486   void set_value(T value)
487   {
488     if (state_ == nullptr)
489       throw std::future_error(std::future_errc::no_state);
490     state_->set_value(std::move(value));
491   }
492   void set_exception(std::exception_ptr exception)
493   {
494     if (state_ == nullptr)
495       throw std::future_error(std::future_errc::no_state);
496     state_->set_exception(std::move(exception));
497   }
498   ~Promise()
499   {
500     if (state_ && state_->get_status() == FutureStatus::not_ready)
501       state_->set_exception(std::make_exception_ptr(
502         std::future_error(std::future_errc::broken_promise)));
503   }
504
505 private:
506   std::shared_ptr<FutureState<T>> state_;
507   bool future_get_ = false;
508 };
509
510 template<>
511 class Promise<void> {
512 public:
513   Promise() : state_(std::make_shared<FutureState<void>>()) {}
514   Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
515   ~Promise()
516   {
517     if (state_ && state_->get_status() == FutureStatus::not_ready)
518       state_->set_exception(std::make_exception_ptr(
519         std::future_error(std::future_errc::broken_promise)));
520   }
521
522   // Move type
523   Promise(Promise const&) = delete;
524   Promise& operator=(Promise const&) = delete;
525   Promise(Promise&& that) :
526     state_(std::move(that.state_)), future_get_(that.future_get_)
527   {
528     that.future_get_ = false;
529   }
530   Promise& operator=(Promise&& that)
531   {
532     this->state_ = std::move(that.state_);
533     this->future_get_ = that.future_get_;
534     that.future_get_ = false;
535     return *this;
536   }
537
538   Future<void> get_future()
539   {
540     if (state_ == nullptr)
541       throw std::future_error(std::future_errc::no_state);
542     if (future_get_)
543       throw std::future_error(std::future_errc::future_already_retrieved);
544     future_get_ = true;
545     return Future<void>(state_);
546   }
547   void set_value()
548   {
549     if (state_ == nullptr)
550       throw std::future_error(std::future_errc::no_state);
551     state_->set_value();
552   }
553   void set_exception(std::exception_ptr exception)
554   {
555     if (state_ == nullptr)
556       throw std::future_error(std::future_errc::no_state);
557     state_->set_exception(std::move(exception));
558   }
559
560 private:
561   std::shared_ptr<FutureState<void>> state_;
562   bool future_get_ = false;
563 };
564
565 }
566 }
567
568 #endif