Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
5fbc4d5fd8e4796599f4b199bcf9c2619183fc2e
[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 <string>
13 #include <utility>
14 #include <memory>
15 #include <functional>
16 #include <future>
17 #include <type_traits>
18
19 #include <xbt/function_types.h>
20 #include <simgrid/simix.h>
21
22 XBT_PUBLIC(void) simcall_run_kernel(std::function<void()> const& code);
23
24 namespace simgrid {
25 namespace simix {
26
27 template<class F>
28 typename std::result_of<F()>::type kernel(F&& code)
29 {
30   typedef typename std::result_of<F()>::type R;
31   std::promise<R> promise;
32   simcall_run_kernel([&]{
33     try {
34       promise.set_value(code());
35     }
36     catch(...) {
37       promise.set_exception(std::current_exception());
38     }
39   });
40   return promise.get_future().get();
41 }
42
43 class Context;
44 class ContextFactory;
45
46 class ContextFactory {
47 private:
48   std::string name_;
49 public:
50
51   ContextFactory(std::string name) : name_(std::move(name)) {}
52   virtual ~ContextFactory();
53   virtual Context* create_context(std::function<void()> code,
54     void_pfn_smxprocess_t cleanup, smx_process_t process) = 0;
55   virtual void run_all() = 0;
56   virtual Context* self();
57   std::string const& name() const
58   {
59     return name_;
60   }
61 private:
62   void declare_context(void* T, std::size_t size);
63 protected:
64   template<class T, class... Args>
65   T* new_context(Args&&... args)
66   {
67     T* context = new T(std::forward<Args>(args)...);
68     this->declare_context(context, sizeof(T));
69     return context;
70   }
71 };
72
73 class Context {
74 private:
75   std::function<void()> code_;
76   void_pfn_smxprocess_t cleanup_func_ = nullptr;
77   smx_process_t process_ = nullptr;
78 public:
79   bool iwannadie;
80 public:
81   Context(std::function<void()> code,
82           void_pfn_smxprocess_t cleanup_func,
83           smx_process_t process);
84   void operator()()
85   {
86     code_();
87   }
88   bool has_code() const
89   {
90     return (bool) code_;
91   }
92   smx_process_t process()
93   {
94     return this->process_;
95   }
96   void set_cleanup(void_pfn_smxprocess_t cleanup)
97   {
98     cleanup_func_ = cleanup;
99   }
100
101   // Virtual methods
102   virtual ~Context();
103   virtual void stop();
104   virtual void suspend() = 0;
105 };
106
107 }
108 }
109
110 #endif