Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[s4u] Move actions by the current actor in the this_actor namespace
[simgrid.git] / include / simgrid / simix.hpp
1 /* Copyright (c) 2007-2010, 2012-2015. 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_SIMIX_HPP
8 #define SIMGRID_SIMIX_HPP
9
10 #include <cstddef>
11
12 #include <exception>
13 #include <string>
14 #include <utility>
15 #include <memory>
16 #include <functional>
17 #include <future>
18 #include <type_traits>
19
20 #include <xbt/function_types.h>
21 #include <simgrid/simix.h>
22
23 XBT_PUBLIC(void) simcall_run_kernel(std::function<void()> const& code);
24
25 namespace simgrid {
26 namespace simix {
27
28 /** Fulfill a promise by executing a given code */
29 template<class R, class F>
30 void fulfill_promise(std::promise<R>& promise, F&& code)
31 {
32   try {
33     promise.set_value(std::forward<F>(code)());
34   }
35   catch(...) {
36     promise.set_exception(std::current_exception());
37   }
38 }
39
40 /** Fulfill a promise by executing a given code
41  *
42  *  This is a special version for `std::promise<void>` because the default
43  *  version does not compile in this case.
44  */
45 template<class F>
46 void fulfill_promise(std::promise<void>& promise, F&& code)
47 {
48   try {
49     std::forward<F>(code)();
50     promise.set_value();
51   }
52   catch(...) {
53     promise.set_exception(std::current_exception());
54   }
55 }
56
57 /** Execute some code in the kernel/maestro
58  *
59  *  This can be used to enforce mutual exclusion with other simcall.
60  *  More importantly, this enforces a deterministic/reproducible ordering
61  *  of the operation with respect to other simcalls.
62  */
63 template<class F>
64 typename std::result_of<F()>::type kernel(F&& code)
65 {
66   // If we are in the maestro, we take the fast path and execute the
67   // code directly without simcall mashalling/unmarshalling/dispatch:
68   if (SIMIX_is_maestro())
69     return std::forward<F>(code)();
70
71   // If we are in the application, pass the code to the maestro which is
72   // executes it for us and reports the result. We use a std::future which
73   // conveniently handles the success/failure value for us.
74   typedef typename std::result_of<F()>::type R;
75   std::promise<R> promise;
76   simcall_run_kernel([&]{
77     xbt_assert(SIMIX_is_maestro(), "Not in maestro");
78     fulfill_promise(promise, std::forward<F>(code));
79   });
80   return promise.get_future().get();
81 }
82
83 class args {
84 private:
85   int argc_ = 0;
86   char** argv_ = nullptr;
87 public:
88
89   // Main constructors
90   args() {}
91
92   void assign(int argc, const char*const* argv)
93   {
94     clear();
95     char** new_argv = xbt_new(char*,argc + 1);
96     for (int i = 0; i < argc; i++)
97       new_argv[i] = xbt_strdup(argv[i]);
98     new_argv[argc] = nullptr;
99     this->argc_ = argc;
100     this->argv_ = new_argv;
101   }
102   args(int argc, const char*const* argv)
103   {
104     this->assign(argc, argv);
105   }
106
107   char** to_argv() const
108   {
109     const int argc = argc_;
110     char** argv = xbt_new(char*, argc + 1);
111     for (int i=0; i< argc; i++)
112       argv[i] = xbt_strdup(argv_[i]);
113     argv[argc] = nullptr;
114     return argv;
115   }
116
117   // Free
118   void clear()
119   {
120     for (int i = 0; i < this->argc_; i++)
121       free(this->argv_[i]);
122     free(this->argv_);
123     this->argc_ = 0;
124     this->argv_ = nullptr;
125   }
126   ~args() { clear(); }
127
128   // Copy
129   args(args const& that)
130   {
131     this->assign(that.argc(), that.argv());
132   }
133   args& operator=(args const& that)
134   {
135     this->assign(that.argc(), that.argv());
136     return *this;
137   }
138
139   // Move:
140   args(args&& that) : argc_(that.argc_), argv_(that.argv_)
141   {
142     that.argc_ = 0;
143     that.argv_ = nullptr;
144   }
145   args& operator=(args&& that)
146   {
147     this->argc_ = that.argc_;
148     this->argv_ = that.argv_;
149     that.argc_ = 0;
150     that.argv_ = nullptr;
151     return *this;
152   }
153
154   int    argc()            const { return argc_; }
155   char** argv()                  { return argv_; }
156   const char*const* argv() const { return argv_; }
157   char* operator[](std::size_t i) { return argv_[i]; }
158 };
159
160 inline std::function<void()> wrap_main(
161   xbt_main_func_t code,  std::shared_ptr<simgrid::simix::args> args)
162 {
163   if (code) {
164     return [=]() {
165       code(args->argc(), args->argv());
166     };
167   }
168   else return std::function<void()>();
169 }
170
171 inline
172 std::function<void()> wrap_main(xbt_main_func_t code, simgrid::simix::args args)
173 {
174   if (code)
175     return wrap_main(code, std::unique_ptr<simgrid::simix::args>(
176       new simgrid::simix::args(std::move(args))));
177   else return std::function<void()>();
178 }
179
180 inline
181 std::function<void()> wrap_main(xbt_main_func_t code, int argc, const char*const* argv)
182 {
183   return wrap_main(code, simgrid::simix::args(argc, argv));
184 }
185
186 class Context;
187 class ContextFactory;
188
189 XBT_PUBLIC_CLASS ContextFactory {
190 private:
191   std::string name_;
192 public:
193
194   ContextFactory(std::string name) : name_(std::move(name)) {}
195   virtual ~ContextFactory();
196   virtual Context* create_context(std::function<void()> code,
197     void_pfn_smxprocess_t cleanup, smx_process_t process) = 0;
198
199   // Optional methods for attaching main() as a context:
200
201   /** Creates a context from the current context of execution
202    *
203    *  This will not work on all implementation of `ContextFactory`.
204    */
205   virtual Context* attach(void_pfn_smxprocess_t cleanup_func, smx_process_t process);
206   virtual Context* create_maestro(std::function<void()> code, smx_process_t process);
207
208   virtual void run_all() = 0;
209   virtual Context* self();
210   std::string const& name() const
211   {
212     return name_;
213   }
214 private:
215   void declare_context(void* T, std::size_t size);
216 protected:
217   template<class T, class... Args>
218   T* new_context(Args&&... args)
219   {
220     T* context = new T(std::forward<Args>(args)...);
221     this->declare_context(context, sizeof(T));
222     return context;
223   }
224 };
225
226 XBT_PUBLIC_CLASS Context {
227 private:
228   std::function<void()> code_;
229   void_pfn_smxprocess_t cleanup_func_ = nullptr;
230   smx_process_t process_ = nullptr;
231 public:
232   bool iwannadie;
233 public:
234   Context(std::function<void()> code,
235           void_pfn_smxprocess_t cleanup_func,
236           smx_process_t process);
237   void operator()()
238   {
239     code_();
240   }
241   bool has_code() const
242   {
243     return (bool) code_;
244   }
245   smx_process_t process()
246   {
247     return this->process_;
248   }
249   void set_cleanup(void_pfn_smxprocess_t cleanup)
250   {
251     cleanup_func_ = cleanup;
252   }
253
254   // Virtual methods
255   virtual ~Context();
256   virtual void stop();
257   virtual void suspend() = 0;
258 };
259
260 XBT_PUBLIC_CLASS AttachContext : public Context {
261 public:
262
263   AttachContext(std::function<void()> code,
264           void_pfn_smxprocess_t cleanup_func,
265           smx_process_t process)
266     : Context(std::move(code), cleanup_func, process)
267   {}
268
269   ~AttachContext();
270
271   /** Called by the context when it is ready to give control
272    *  to the maestro.
273    */
274   virtual void attach_start() = 0;
275
276   /** Called by the context when it has finished its job */
277   virtual void attach_stop() = 0;
278 };
279
280 XBT_PUBLIC(void) set_maestro(std::function<void()> code);
281 XBT_PUBLIC(void) create_maestro(std::function<void()> code);
282
283 }
284 }
285
286 /*
287  * Type of function that creates a process.
288  * The function must accept the following parameters:
289  * void* process: the process created will be stored there
290  * const char *name: a name for the object. It is for user-level information and can be NULL
291  * xbt_main_func_t code: is a function describing the behavior of the process
292  * void *data: data a pointer to any data one may want to attach to the new object.
293  * sg_host_t host: the location where the new process is executed
294  * int argc, char **argv: parameters passed to code
295  * xbt_dict_t pros: properties
296  */
297 typedef smx_process_t (*smx_creation_func_t) (
298                                       /* name */ const char*,
299                                       std::function<void()> code,
300                                       /* userdata */ void*,
301                                       /* hostname */ const char*,
302                                       /* kill_time */ double,
303                                       /* props */ xbt_dict_t,
304                                       /* auto_restart */ int,
305                                       /* parent_process */ smx_process_t);
306
307 extern "C"
308 XBT_PUBLIC(void) SIMIX_function_register_process_create(smx_creation_func_t function);
309
310 XBT_PUBLIC(smx_process_t) simcall_process_create(const char *name,
311                                           std::function<void()> code,
312                                           void *data,
313                                           const char *hostname,
314                                           double kill_time,
315                                           xbt_dict_t properties,
316                                           int auto_restart);
317
318 XBT_PUBLIC(smx_timer_t) SIMIX_timer_set(double date, std::function<void()> callback);
319
320 template<class R, class T> inline
321 XBT_PUBLIC(smx_timer_t) SIMIX_timer_set(double date, R(*callback)(T*), T* arg)
322 {
323   return SIMIX_timer_set(date, [=](){ callback(arg); });
324 }
325
326 #endif