Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[simix] Execute future callbacks in the main loop
[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 #include <xbt/future.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   void schedule(simgrid::xbt::Task<void()>&& job);
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(!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 mast 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 becase 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       std::rethrow_exception(std::move(exception));
125     }
126   }
127
128 private:
129   FutureStatus status_ = FutureStatus::not_ready;
130   std::exception_ptr exception_;
131   simgrid::xbt::Task<void()> continuation_;
132 };
133
134 /** Shared state for future and promises
135  *
136  *  You are not expected to use them directly but to create them
137  *  implicitely through a @ref simgrid::kernel::Promise.
138  *  Alternatively kernel operations could inherit or contain FutureState
139  *  if they are managed with @ref std::shared_ptr.
140  **/
141 template<class T>
142 class FutureState : public FutureStateBase {
143 public:
144
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 std::move(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 *value_;
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>
207 void bindPromise(Promise<T> promise, Future<T> future)
208 {
209   struct PromiseBinder {
210   public:
211     PromiseBinder(Promise<T> promise) : promise_(std::move(promise)) {}
212     void operator()(Future<T> future)
213     {
214       simgrid::xbt::setPromise(promise_, future);
215     }
216   private:
217     Promise<T> promise_;
218   };
219   future.then_(PromiseBinder(std::move(promise)));
220 }
221
222 template<class T> Future<T> unwrapFuture(Future<Future<T>> future);
223
224 /** Result of some (probably) asynchronous operation in the SimGrid kernel
225  *
226  * @ref simgrid::simix::Future and @ref simgrid::simix::Future provide an
227  * abstration for asynchronous stuff happening in the SimGrid kernel. They
228  * are based on C++1z futures.
229  *
230  * The future represents a value which will be available at some point when this
231  * asynchronous operaiont is finished. Alternatively, if this operations fails,
232  * the result of the operation might be an exception.
233  *
234  *  As the operation is possibly no terminated yet, we cannot get the result
235  *  yet. Moreover, as we cannot block in the SimGrid kernel we cannot wait for
236  *  it. However, we can attach some code/callback/continuation which will be
237  *  executed when the operation terminates.
238  *
239  *  Example of the API (`simgrid::kernel::createProcess` does not exist):
240  *  <pre>
241  *  // Create a new process using the Worker code, this process returns
242  *  // a std::string:
243  *  simgrid::kernel::Future<std::string> future =
244  *     simgrid::kernel::createProcess("worker42", host, Worker(42));
245  *  // At this point, we just created the process so the result is not available.
246  *  // However, we can attach some work do be done with this result:
247  *  future.then([](simgrid::kernel::Future<std::string> result) {
248  *    // This code is called when the operation is completed so the result is
249  *    // available:
250  *    try {
251  *      // Try to get value, this might throw an exception if the operation
252  *      // failed (such as an exception throwed by the worker process):
253  *      std::string value = result.get();
254  *      XBT_INFO("Value: %s", value.c_str());
255  *    }
256  *    catch(std::exception& e) {
257  *      // This is an exception from the asynchronous operation:
258  *      XBT_INFO("Error: %e", e.what());
259  *    }
260  *  );
261  *  </pre>
262  *
263  *  This is based on C++1z @ref std::future but with some differences:
264  *
265  *  * there is no thread synchronization (atomic, mutex, condition variable,
266  *    etc.) because everything happens in the SimGrid event loop;
267  *
268  *  * it is purely asynchronous, you are expected to use `.then()`;
269  *
270  *  * inside the `.then()`, `.get()` can be used;
271  *
272  *  * `.get()` can only be used when `.is_ready()` (as everything happens in
273  *     a single-thread, the future would be guaranted to deadlock if `.get()`
274  *     is called when the future is not ready);
275  *
276  *  * there is no future chaining support for now (`.then().then()`);
277  *
278  *  * there is no sharing (`shared_future`) for now.
279  */
280 template<class T>
281 class Future {
282 public:
283   Future() = default;
284   Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
285
286   // Move type:
287   Future(Future&) = delete;
288   Future& operator=(Future&) = delete;
289   Future(Future&& that) : state_(std::move(that.state_)) {}
290   Future& operator=(Future&& that)
291   {
292     state_ = std::move(that.state_);
293     return *this;
294   }
295
296   /** Whether the future is valid:.
297    *
298    *  A future which as been used (`.then` of `.get`) becomes invalid.
299    *
300    *  We can use `.then` on a valid future.
301    */
302   bool valid() const
303   {
304     return state_ != nullptr;
305   }
306
307   /** Whether the future is ready
308    *
309    *  A future is ready when it has an associated value or exception.
310    *
311    *  We can use `.get()` on ready futures.
312    **/
313   bool is_ready() const
314   {
315     return state_ != nullptr && state_->is_ready();
316   }
317
318   /** Attach a continuation to this future
319    *
320    *  This is like .then() but avoid the creation of a new future.
321    */
322   template<class F>
323   void then_(F continuation)
324   {
325     if (state_ == nullptr)
326       throw std::future_error(std::future_errc::no_state);
327     // Give shared-ownership to the continuation:
328     auto state = std::move(state_);
329     state->set_continuation(simgrid::xbt::makeTask(
330       std::move(continuation), state));
331   }
332
333   /** Attach a continuation to this future
334    *
335    *  This version never does future unwrapping.
336    */
337   template<class F>
338   auto thenNoUnwrap(F continuation)
339   -> Future<decltype(continuation(std::move(*this)))>
340   {
341     typedef decltype(continuation(std::move(*this))) R;
342     if (state_ == nullptr)
343       throw std::future_error(std::future_errc::no_state);
344     auto state = std::move(state_);
345     // Create a new future...
346     Promise<R> promise;
347     Future<R> future = promise.get_future();
348     // ...and when the current future is ready...
349     state->set_continuation(simgrid::xbt::makeTask(
350       [](Promise<R> promise, std::shared_ptr<FutureState<T>> state, F continuation) {
351         // ...set the new future value by running the continuation.
352         Future<T> future(std::move(state));
353         simgrid::xbt::fulfillPromise(promise,[&]{
354           return continuation(std::move(future));
355         });
356       },
357       std::move(promise), state, std::move(continuation)));
358     return std::move(future);
359   }
360
361   /** Attach a continuation to this future
362    *
363    *  The future must be valid in order to make this call.
364    *  The continuation is executed when the future becomes ready.
365    *  The future becomes invalid after this call.
366    *
367    * @param continuation This function is called with a ready future
368    *                     the future is ready
369    * @exception std::future_error no state is associated with the future
370    */
371   template<class F>
372   auto then(F continuation)
373   -> typename std::enable_if<
374        !is_future<decltype(continuation(std::move(*this)))>::value,
375        Future<decltype(continuation(std::move(*this)))>
376      >::type
377   {
378     return this->thenNoUnwrap(std::move(continuation));
379   }
380
381   /** Attach a continuation to this future (future chaining) */
382   template<class F>
383   auto then(F continuation)
384   -> typename std::enable_if<
385        is_future<decltype(continuation(std::move(*this)))>::value,
386        decltype(continuation(std::move(*this)))
387      >::type
388   {
389     return unwrapFuture(this->thenNoUnwap(std::move(continuation)));
390   }
391
392   /** Get the value from the future
393    *
394    *  This is expected to be called
395    *
396    *  The future must be valid and ready in order to make this call.
397    *  @ref std::future blocks when the future is not ready but we are
398    *  completely single-threaded so blocking would be a deadlock.
399    *  After the call, the future becomes invalid.
400    *
401    *  @return                      value of the future
402    *  @exception any               Exception from the future
403    *  @exception std::future_error no state is associated with the future
404    */
405   T get()
406   {
407     if (state_ == nullptr)
408       throw std::future_error(std::future_errc::no_state);
409     std::shared_ptr<FutureState<T>> state = std::move(state_);
410     return state->get();
411   }
412
413 private:
414   std::shared_ptr<FutureState<T>> state_;
415 };
416
417 template<class T>
418 Future<T> unwrapFuture(Future<Future<T>> future)
419 {
420   Promise<T> promise;
421   Future<T> result = promise.get_future();
422   bindPromise(std::move(promise), std::move(future));
423   return std::move(result);
424 }
425
426 /** Producer side of a @simgrid::kernel::Future
427  *
428  *  A @ref Promise is connected to some `Future` and can be used to
429  *  set its result.
430  *
431  *  Similar to @ref std::promise
432  *
433  *  <code>
434  *  // Create a promise and a future:
435  *  auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
436  *  auto future = promise->get_future();
437  *
438  *  SIMIX_timer_set(date, [promise] {
439  *    try {
440  *      int value = compute_the_value();
441  *      if (value < 0)
442  *        throw std::logic_error("Bad value");
443  *      // Whenever the operation is completed, we set the value
444  *      // for the future:
445  *      promise.set_value(value);
446  *    }
447  *    catch (...) {
448  *      // If an error occured, we can set an exception which
449  *      // will be throwed buy future.get():
450  *      promise.set_exception(std::current_exception());
451  *    }
452  *  });
453  *
454  *  // Return the future to the caller:
455  *  return future;
456  *  </code>
457  **/
458 template<class T>
459 class Promise {
460 public:
461   Promise() : state_(std::make_shared<FutureState<T>>()) {}
462   Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
463
464   // Move type
465   Promise(Promise const&) = delete;
466   Promise& operator=(Promise const&) = delete;
467   Promise(Promise&& that) :
468     state_(std::move(that.state_)), future_get_(that.future_get_)
469   {
470     that.future_get_ = false;
471   }
472
473   Promise& operator=(Promise&& that)
474   {
475     this->state_ = std::move(that.state_);
476     this->future_get_ = that.future_get_;
477     that.future_get_ = false;
478     return *this;
479   }
480   Future<T> get_future()
481   {
482     if (state_ == nullptr)
483       throw std::future_error(std::future_errc::no_state);
484     if (future_get_)
485       throw std::future_error(std::future_errc::future_already_retrieved);
486     future_get_ = true;
487     return Future<T>(state_);
488   }
489   void set_value(T value)
490   {
491     if (state_ == nullptr)
492       throw std::future_error(std::future_errc::no_state);
493     state_->set_value(std::move(value));
494   }
495   void set_exception(std::exception_ptr exception)
496   {
497     if (state_ == nullptr)
498       throw std::future_error(std::future_errc::no_state);
499     state_->set_exception(std::move(exception));
500   }
501   ~Promise()
502   {
503     if (state_ && state_->get_status() == FutureStatus::not_ready)
504       state_->set_exception(std::make_exception_ptr(
505         std::future_error(std::future_errc::broken_promise)));
506   }
507
508 private:
509   std::shared_ptr<FutureState<T>> state_;
510   bool future_get_ = false;
511 };
512
513 template<>
514 class Promise<void> {
515 public:
516   Promise() : state_(std::make_shared<FutureState<void>>()) {}
517   Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
518   ~Promise()
519   {
520     if (state_ && state_->get_status() == FutureStatus::not_ready)
521       state_->set_exception(std::make_exception_ptr(
522         std::future_error(std::future_errc::broken_promise)));
523   }
524
525   // Move type
526   Promise(Promise const&) = delete;
527   Promise& operator=(Promise const&) = delete;
528   Promise(Promise&& that) :
529     state_(std::move(that.state_)), future_get_(that.future_get_)
530   {
531     that.future_get_ = false;
532   }
533   Promise& operator=(Promise&& that)
534   {
535     this->state_ = std::move(that.state_);
536     this->future_get_ = that.future_get_;
537     that.future_get_ = false;
538     return *this;
539   }
540
541   Future<void> get_future()
542   {
543     if (state_ == nullptr)
544       throw std::future_error(std::future_errc::no_state);
545     if (future_get_)
546       throw std::future_error(std::future_errc::future_already_retrieved);
547     future_get_ = true;
548     return Future<void>(state_);
549   }
550   void set_value()
551   {
552     if (state_ == nullptr)
553       throw std::future_error(std::future_errc::no_state);
554     state_->set_value();
555   }
556   void set_exception(std::exception_ptr exception)
557   {
558     if (state_ == nullptr)
559       throw std::future_error(std::future_errc::no_state);
560     state_->set_exception(std::move(exception));
561   }
562
563 private:
564   std::shared_ptr<FutureState<void>> state_;
565   bool future_get_ = false;
566 };
567
568 }
569 }
570
571 #endif