Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[simix] .wait() and .is_ready() on simix::Future
[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 <boost/optional.hpp>
11
12 #include <xbt/base.h>
13 #include <xbt/functional.hpp>
14
15 #include <functional>
16 #include <future>
17 #include <memory>
18 #include <utility>
19 #include <type_traits>
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 /** Bases stuff for all @ref simgrid::kernel::FutureState<T> */
39 class FutureStateBase {
40 public:
41   // No copy/move:
42   FutureStateBase(FutureStateBase const&) = delete;
43   FutureStateBase& operator=(FutureStateBase const&) = delete;
44
45   void set_exception(std::exception_ptr exception)
46   {
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);
51     this->set_ready();
52   }
53
54   void set_continuation(simgrid::xbt::Task<void()> continuation)
55   {
56     xbt_assert(!continuation_);
57     switch (status_) {
58     case FutureStatus::done:
59       // This is not supposed to happen if continuation is set
60       // via the Promise:
61       xbt_die("Set continuation on finished future");
62       break;
63     case FutureStatus::ready:
64       // The future is ready, execute the continuation directly.
65       // We might execute it from the event loop instead:
66       continuation();
67       break;
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);
72       break;
73     }
74   }
75
76   FutureStatus get_status() const
77   {
78     return status_;
79   }
80
81   bool is_ready() const
82   {
83     return status_ == FutureStatus::ready;
84   }
85
86 protected:
87   FutureStateBase() {}
88   ~FutureStateBase() {};
89
90   /** Set the future as ready and trigger the continuation */
91   void set_ready()
92   {
93     status_ = FutureStatus::ready;
94     if (continuation_) {
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_);
99       continuation();
100     }
101   }
102
103   /** Set the future as done and raise an exception if any
104    *
105    *  This does half the job of `.get()`.
106    **/
107   void resolve()
108   {
109     if (status_ != FutureStatus::ready)
110       xbt_die("Deadlock: this future is not ready");
111     status_ = FutureStatus::done;
112     if (exception_) {
113       std::exception_ptr exception = std::move(exception_);
114       std::rethrow_exception(std::move(exception));
115     }
116   }
117
118 private:
119   FutureStatus status_ = FutureStatus::not_ready;
120   std::exception_ptr exception_;
121   simgrid::xbt::Task<void()> continuation_;
122 };
123
124 /** Shared state for future and promises
125  *
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.
130  **/
131 template<class T>
132 class FutureState : public FutureStateBase {
133 public:
134
135   void set_value(T value)
136   {
137     if (this->get_status() != FutureStatus::not_ready)
138       throw std::future_error(std::future_errc::promise_already_satisfied);
139     value_ = std::move(value);
140     this->set_ready();
141   }
142
143   T get()
144   {
145     this->resolve();
146     xbt_assert(this->value_);
147     auto result = std::move(this->value_.get());
148     this->value_ = boost::optional<T>();
149     return std::move(result);
150   }
151
152 private:
153   boost::optional<T> value_;
154 };
155
156 template<class T>
157 class FutureState<T&> : public FutureStateBase {
158 public:
159   void set_value(T& value)
160   {
161     if (this->get_status() != FutureStatus::not_ready)
162       throw std::future_error(std::future_errc::promise_already_satisfied);
163     value_ = &value;
164     this->set_ready();
165   }
166
167   T& get()
168   {
169     this->resolve();
170     xbt_assert(this->value_);
171     T* result = value_;
172     value_ = nullptr;
173     return *value_;
174   }
175
176 private:
177   T* value_ = nullptr;
178 };
179
180 template<>
181 class FutureState<void> : public FutureStateBase {
182 public:
183   void set_value()
184   {
185     if (this->get_status() != FutureStatus::not_ready)
186       throw std::future_error(std::future_errc::promise_already_satisfied);
187     this->set_ready();
188   }
189
190   void get()
191   {
192     this->resolve();
193   }
194 };
195
196 /** Result of some (probably) asynchronous operation in the SimGrid kernel
197  *
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.
201  *
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.
205  *
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.
210  *
211  *  Example of the API (`simgrid::kernel::createProcess` does not exist):
212  *  <pre>
213  *  // Create a new process using the Worker code, this process returns
214  *  // a std::string:
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
221  *    // available:
222  *    try {
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());
227  *    }
228  *    catch(std::exception& e) {
229  *      // This is an exception from the asynchronous operation:
230  *      XBT_INFO("Error: %e", e.what());
231  *    }
232  *  );
233  *  </pre>
234  *
235  *  This is based on C++1z @ref std::future but with some differences:
236  *
237  *  * there is no thread synchronization (atomic, mutex, condition variable,
238  *    etc.) because everything happens in the SimGrid event loop;
239  *
240  *  * it is purely asynchronous, you are expected to use `.then()`;
241  *
242  *  * inside the `.then()`, `.get()` can be used;
243  *
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);
247  *
248  *  * there is no future chaining support for now (`.then().then()`);
249  *
250  *  * there is no sharing (`shared_future`) for now.
251  */
252 template<class T>
253 class Future {
254 public:
255   Future() {}
256   Future(std::shared_ptr<FutureState<T>> state): state_(std::move(state)) {}
257
258   // Move type:
259   Future(Future&) = delete;
260   Future& operator=(Future&) = delete;
261   Future(Future&& that) : state_(std::move(that.state_)) {}
262   Future& operator=(Future&& that)
263   {
264     state_ = std::move(that.state_);
265     return *this;
266   }
267
268   /** Whether the future is valid:.
269    *
270    *  A future which as been used (`.then` of `.get`) becomes invalid.
271    *
272    *  We can use `.then` on a valid future.
273    */
274   bool valid() const
275   {
276     return state_ != nullptr;
277   }
278
279   /** Whether the future is ready
280    *
281    *  A future is ready when it has an associated value or exception.
282    *
283    *  We can use `.get()` on ready futures.
284    **/
285   bool is_ready() const
286   {
287     return state_ != nullptr && state_->is_ready();
288   }
289
290   /** Attach a continuation to this future
291    *
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.
295    *
296    *  We don't support future chaining for now (`.then().then()`).
297    *
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
301    */
302   template<class F>
303   void then(F continuation)
304   {
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));
311   }
312
313   /** Get the value from the future
314    *
315    *  This is expected to be called
316    *
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.
321    *
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
325    */
326   T get()
327   {
328     if (state_ == nullptr)
329       throw std::future_error(std::future_errc::no_state);
330     std::shared_ptr<FutureState<T>> state = std::move(state_);
331     return state->get();
332   }
333
334 private:
335   std::shared_ptr<FutureState<T>> state_;
336 };
337
338 /** Producer side of a @simgrid::kernel::Future
339  *
340  *  A @ref Promise is connected to some `Future` and can be used to
341  *  set its result.
342  *
343  *  Similar to @ref std::promise
344  *
345  *  <code>
346  *  // Create a promise and a future:
347  *  auto promise = std::make_shared<simgrid::kernel::Promise<T>>();
348  *  auto future = promise->get_future();
349  *
350  *  SIMIX_timer_set(date, [promise] {
351  *    try {
352  *      int value = compute_the_value();
353  *      if (value < 0)
354  *        throw std::logic_error("Bad value");
355  *      // Whenever the operation is completed, we set the value
356  *      // for the future:
357  *      promise.set_value(value);
358  *    }
359  *    catch (...) {
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());
363  *    }
364  *  });
365  *
366  *  // Return the future to the caller:
367  *  return future;
368  *  </code>
369  **/
370 template<class T>
371 class Promise {
372 public:
373   Promise() : state_(std::make_shared<FutureState<T>>()) {}
374   Promise(std::shared_ptr<FutureState<T>> state) : state_(std::move(state)) {}
375
376   // Move type
377   Promise(Promise&) = delete;
378   Promise& operator=(Promise&) = delete;
379   Promise(Promise&& that) :
380     state_(std::move(that.state_)), future_get_(that.future_set)
381   {
382     that.future_get_ = false;
383   }
384
385   Promise& operator=(Promise&& that)
386   {
387     this->state_ = std::move(that.state_);
388     this->future_get_ = that.future_get_;
389     that.future_get_ = false;
390     return *this;
391   }
392   Future<T> get_future()
393   {
394     if (state_ == nullptr)
395       throw std::future_error(std::future_errc::no_state);
396     if (future_get_)
397       throw std::future_error(std::future_errc::future_already_retrieved);
398     future_get_ = true;
399     return Future<T>(state_);
400   }
401   void set_value(T value)
402   {
403     if (state_ == nullptr)
404       throw std::future_error(std::future_errc::no_state);
405     state_->set_value(std::move(value));
406   }
407   void set_exception(std::exception_ptr exception)
408   {
409     if (state_ == nullptr)
410       throw std::future_error(std::future_errc::no_state);
411     state_->set_exception(std::move(exception));
412   }
413   ~Promise()
414   {
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)));
418   }
419
420 private:
421   std::shared_ptr<FutureState<T>> state_;
422   bool future_get_ = false;
423 };
424
425 template<>
426 class Promise<void> {
427 public:
428   Promise() : state_(std::make_shared<FutureState<void>>()) {}
429   Promise(std::shared_ptr<FutureState<void>> state) : state_(std::move(state)) {}
430   ~Promise()
431   {
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)));
435   }
436
437   // Move type
438   Promise(Promise&) = delete;
439   Promise& operator=(Promise&) = delete;
440   Promise(Promise&& that) :
441     state_(std::move(that.state_)), future_get_(that.future_get_)
442   {
443     that.future_get_ = false;
444   }
445   Promise& operator=(Promise&& that)
446   {
447     this->state_ = std::move(that.state_);
448     this->future_get_ = that.future_get_;
449     that.future_get_ = false;
450     return *this;
451   }
452
453   Future<void> get_future()
454   {
455     if (state_ == nullptr)
456       throw std::future_error(std::future_errc::no_state);
457     if (future_get_)
458       throw std::future_error(std::future_errc::future_already_retrieved);
459     future_get_ = true;
460     return Future<void>(state_);
461   }
462   void set_value()
463   {
464     if (state_ == nullptr)
465       throw std::future_error(std::future_errc::no_state);
466     state_->set_value();
467   }
468   void set_exception(std::exception_ptr exception)
469   {
470     if (state_ == nullptr)
471       throw std::future_error(std::future_errc::no_state);
472     state_->set_exception(std::move(exception));
473   }
474
475 private:
476   std::shared_ptr<FutureState<void>> state_;
477   bool future_get_ = false;
478 };
479
480 }
481 }
482
483 #endif