Logo AND Algorithmique Numérique Distribuée

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