Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[simgrid.git] / include / simgrid / s4u / actor.hpp
1 /* Copyright (c) 2006-2016. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SIMGRID_S4U_ACTOR_HPP
7 #define SIMGRID_S4U_ACTOR_HPP
8
9 #include <atomic>
10 #include <functional>
11 #include <future>
12 #include <memory>
13 #include <stdexcept>
14 #include <type_traits>
15
16 #include <xbt/base.h>
17 #include <xbt/functional.hpp>
18
19 #include <simgrid/simix.h>
20 #include <simgrid/s4u/forward.hpp>
21
22 namespace simgrid {
23 namespace s4u {
24
25 /** @ingroup s4u_api
26  * 
27  * An actor is an independent stream of execution in your distributed application.
28  *
29  * You can think of an actor as a process in your distributed application, or as a thread in a multithreaded program.
30  * This is the only component in SimGrid that actually does something on its own, executing its own code. 
31  * A resource will not get used if you don't schedule activities on them. This is the code of Actors that create and schedule these activities.
32  * 
33  * An actor is located on a (simulated) host, but it can interact
34  * with the whole simulated platform.
35  * 
36  * The s4u::Actor API is strongly inspired from the C++11 threads.
37  * The <a href="http://en.cppreference.com/w/cpp/thread">documentation 
38  * of this standard</a> may help to understand the philosophy of the S4U
39  * Actors. 
40  * 
41  * @section s4u_actor_def Defining the skeleton of an Actor
42  * 
43  * %As in the <a href="http://en.cppreference.com/w/cpp/thread">C++11
44  * standard</a>, you can declare the code of your actor either as a
45  * pure function or as an object. It is very simple with functions:
46  * 
47  * @code{.cpp}
48  * #include "s4u/actor.hpp"
49  * 
50  * // Declare the code of your worker
51  * void worker() {
52  *   printf("Hello s4u");
53  *   simgrid::s4u::this_actor::execute(5*1024*1024); // Get the worker executing a task of 5 MFlops
54  * };
55  * 
56  * // From your main or from another actor, create your actor on the host Jupiter
57  * // The following line actually creates a new actor, even if there is no "new". 
58  * Actor("Alice", simgrid::s4u::Host::by_name("Jupiter"), worker);
59  * @endcode
60  * 
61  * But some people prefer to encapsulate their actors in classes and
62  * objects to save the actor state in a cleanly dedicated location.
63  * The syntax is slightly more complicated, but not much.
64  * 
65  * @code{.cpp}
66  * #include "s4u/actor.hpp"
67  * 
68  * // Declare the class representing your actors
69  * class Worker {
70  * public:
71  *   void operator()() { // Two pairs of () because this defines the method called ()
72  *     printf("Hello s4u");
73  *     simgrid::s4u::this_actor::execute(5*1024*1024); // Get the worker executing a task of 5 MFlops
74  *   }
75  * };
76  * 
77  * // From your main or from another actor, create your actor. Note the () after Worker
78  * Actor("Bob", simgrid::s4u::Host::by_name("Jupiter"), Worker());
79  * @endcode
80  * 
81  * @section s4u_actor_flesh Fleshing your actor
82  * 
83  * The body of your actor can use the functions of the
84  * simgrid::s4u::this_actor namespace to interact with the world.
85  * This namespace contains the methods to start new activities
86  * (executions, communications, etc), and to get informations about
87  * the currently running thread (its location, etc).
88  * 
89  * Please refer to the @link simgrid::s4u::this_actor full API @endlink.
90  *
91  * 
92  * @section s4u_actor_deploy Using a deployment file
93  * 
94  * @warning This is currently not working with S4U. Sorry about that.
95  * 
96  * The best practice is to use an external deployment file as
97  * follows, because it makes it easier to test your application in
98  * differing settings. Load this file with
99  * s4u::Engine::loadDeployment() before the simulation starts. 
100  * Refer to the @ref deployment section for more information.
101  * 
102  * @code{.xml}
103  * <?xml version='1.0'?>
104  * <!DOCTYPE platform SYSTEM "http://simgrid.gforge.inria.fr/simgrid/simgrid.dtd">
105  * <platform version="4">
106  * 
107  *   <!-- Start a process called 'master' on the host called 'Tremblay' -->
108  *   <process host="Tremblay" function="master">
109  *      <!-- Here come the parameter that you want to feed to this instance of master -->
110  *      <argument value="20"/>        <!-- argv[1] -->
111  *      <argument value="50000000"/>  <!-- argv[2] -->
112  *      <argument value="1000000"/>   <!-- argv[3] -->
113  *      <argument value="5"/>         <!-- argv[4] -->
114  *   </process>
115  * 
116  *   <!-- Start a process called 'worker' on the host called 'Jupiter' -->
117  *   <process host="Jupiter" function="worker"/> <!-- Don't provide any parameter ->>
118  * 
119  * </platform>
120  * @endcode
121  * 
122  *  @{
123  */
124
125 /** @brief Simulation Agent (see \ref s4u_actor)*/
126 XBT_PUBLIC_CLASS Actor {
127 private:
128   /** Wrap a (possibly non-copyable) single-use task into a `std::function` */
129   template<class F, class... Args>
130   class Task {
131   public:
132     Task(F&& code, Args&&... args) :
133       code_(std::forward<F>(code)),
134       args_(std::forward<Args>(args)...)
135     {}
136     void operator()()
137     {
138       if (done_.test_and_set())
139         throw std::logic_error("Actor task already executed");
140       simgrid::xbt::apply(std::move(code_), std::move(args_));
141     }
142   private:
143     std::atomic_flag done_ = ATOMIC_FLAG_INIT;
144     F code_;
145     std::tuple<Args...> args_;
146   };
147   /** Wrap a (possibly non-copyable) single-use task into a `std::function` */
148   template<class F, class... Args>
149   static std::function<void()> wrap_task(F f, Args... args)
150   {
151     std::shared_ptr<Task<F, Args...>> task(
152       new Task<F, Args...>(std::move(f), std::move(args)...));
153     return [=] {
154       (*task)();
155     };
156   }
157 public:
158   Actor() : pimpl_(nullptr) {}
159   Actor(smx_process_t smx_proc) :
160     pimpl_(SIMIX_process_ref(smx_proc)) {}
161   ~Actor()
162   {
163     SIMIX_process_unref(pimpl_);
164   }
165
166   // Copy+move (with the copy-and-swap idiom):
167   Actor(Actor const& actor) : pimpl_(SIMIX_process_ref(actor.pimpl_)) {}
168   friend void swap(Actor& first, Actor& second)
169   {
170     using std::swap;
171     swap(first.pimpl_, second.pimpl_);
172   }
173   Actor& operator=(Actor actor)
174   {
175     swap(*this, actor);
176     return *this;
177   }
178   Actor(Actor&& actor) : pimpl_(nullptr)
179   {
180     swap(*this, actor);
181   }
182
183   /** Create an actor using a function
184    *
185    *  If the actor is restarted, the actor has a fresh copy of the function.
186    */
187   Actor(const char* name, s4u::Host *host, double killTime, std::function<void()> code);
188
189   Actor(const char* name, s4u::Host *host, std::function<void()> code)
190     : Actor(name, host, -1.0d, std::move(code)) {};
191
192   /** Create an actor using code
193    *
194    *  Using this constructor, move-only type can be used. The consequence is
195    *  that we cannot copy the value and restart the process in its initial
196    *  state. In order to use auto-restart, an explicit `function` must be passed
197    *  instead.
198    */
199   template<class F, class... Args,
200     // This constructor is enabled only if the call code(args...) is valid:
201     typename = typename std::result_of<F(Args...)>::type
202     >
203   Actor(const char* name, s4u::Host *host, F code, Args... args) :
204     Actor(name, host, wrap_task(std::move(code), std::move(args)...))
205   {}
206
207   /** Retrieves the actor that have the given PID (or NULL if not existing) */
208   //static Actor *byPid(int pid); not implemented
209
210   /** Retrieves the name of that actor */
211   const char* getName();
212   /** Retrieves the host on which that actor is running */
213   s4u::Host *getHost();
214   /** Retrieves the PID of that actor */
215   int getPid();
216
217   /** If set to true, the actor will automatically restart when its host reboots */
218   void setAutoRestart(bool autorestart);
219   /** Sets the time at which that actor should be killed */
220   void setKillTime(double time);
221   /** Retrieves the time at which that actor will be killed (or -1 if not set) */
222   double getKillTime();
223
224   /** Ask the actor to die.
225    *
226    * It will only notice your request when doing a simcall next time (a communication or similar).
227    * SimGrid sometimes have issues when you kill actors that are currently communicating and such. We are working on it to fix the issues.
228    */
229   void kill();
230
231   static void kill(int pid);
232   
233   /**
234    * Wait for the actor to finish.
235    */ 
236   void join();
237   
238   // Static methods on all actors:
239
240   /** Ask kindly to all actors to die. Only the issuer will survive. */
241   static void killAll();
242
243 private:
244   smx_process_t pimpl_ = nullptr;
245 };
246
247 /** @ingroup s4u_api
248  *  @brief Static methods working on the current actor (see @ref s4u::Actor) */
249 namespace this_actor {
250
251   /** Block the actor sleeping for that amount of seconds (may throws hostFailure) */
252   XBT_PUBLIC(void) sleep(double duration);
253
254   /** Block the actor, computing the given amount of flops */
255   XBT_PUBLIC(e_smx_state_t) execute(double flop);
256
257   /** Block the actor until it gets a message from the given mailbox.
258    *
259    * See \ref Comm for the full communication API (including non blocking communications).
260    */
261   XBT_PUBLIC(void*) recv(Mailbox &chan);
262
263   /** Block the actor until it delivers a message of the given simulated size to the given mailbox
264    *
265    * See \ref Comm for the full communication API (including non blocking communications).
266   */
267   XBT_PUBLIC(void) send(Mailbox &chan, void*payload, size_t simulatedSize);
268
269 };
270
271 /** @} */
272
273 }} // namespace simgrid::s4u
274
275
276 #endif /* SIMGRID_S4U_ACTOR_HPP */