Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
implement Activity::destroy when you want to clean up things
[simgrid.git] / include / simgrid / s4u / Activity.hpp
1 /* Copyright (c) 2006-2021. 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_ACTIVITY_HPP
7 #define SIMGRID_S4U_ACTIVITY_HPP
8
9 #include <xbt/asserts.h>
10 #include <algorithm>
11 #include <atomic>
12 #include <set>
13 #include <simgrid/forward.h>
14 #include <stdexcept>
15 #include <string>
16 #include <vector>
17 #include <xbt/signal.hpp>
18 #include <xbt/utility.hpp>
19
20 XBT_LOG_EXTERNAL_CATEGORY(s4u_activity);
21
22 namespace simgrid {
23 namespace s4u {
24
25 /** @brief Activities
26  *
27  * This class is the ancestor of every activities that an actor can undertake.
28  * That is, activities are all the things that do take time to the actor in the simulated world.
29  */
30 class XBT_PUBLIC Activity {
31   friend Comm;
32   friend Exec;
33   friend Io;
34 #ifndef DOXYGEN
35   friend std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename);
36 #endif
37
38 public:
39   // enum class State { ... }
40   XBT_DECLARE_ENUM_CLASS(State, INITED, STARTING, STARTED, FAILED, CANCELED, FINISHED);
41
42   virtual bool is_assigned() const = 0;
43   virtual bool dependencies_solved() const { return dependencies_.empty(); }
44   virtual unsigned long is_waited_by() const { return successors_.size(); }
45   const std::set<ActivityPtr>& get_dependencies() const { return dependencies_; }
46   const std::vector<ActivityPtr>& get_successors() const { return successors_; }
47
48 protected:
49   Activity()  = default;
50   virtual ~Activity() = default;
51   void destroy();
52
53   void release_dependencies()
54   {
55     while (not successors_.empty()) {
56       ActivityPtr b = successors_.back();
57       XBT_CVERB(s4u_activity, "Remove a dependency from '%s' on '%s'", get_cname(), b->get_cname());
58       b->dependencies_.erase(this);
59       if (b->dependencies_solved()) {
60         b->vetoable_start();
61       }
62       successors_.pop_back();
63     }
64   }
65
66   void add_successor(ActivityPtr a)
67   {
68     if(this == a)
69       throw std::invalid_argument("Cannot be its own successor");
70     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
71     if (p != successors_.end())
72       throw std::invalid_argument("Dependency already exists");
73
74     successors_.push_back(a);
75     a->dependencies_.insert({this});
76   }
77
78   void remove_successor(ActivityPtr a)
79   {
80     if(this == a)
81       throw std::invalid_argument("Cannot ask to remove itself from successors list");
82
83     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
84     if (p != successors_.end()){
85       successors_.erase(p);
86       a->dependencies_.erase({this});
87     } else
88       throw std::invalid_argument("Dependency does not exist. Can not be removed.");
89   }
90
91   static std::set<Activity*>* vetoed_activities_;
92
93 public:
94   /*! Signal fired each time that the activity fails to start because of a veto (e.g., unsolved dependency or no
95    * resource assigned) */
96   static xbt::signal<void(Activity&)> on_veto;
97   /*! Signal fired when theactivity completes  (either normally, cancelled or failed) */
98   static xbt::signal<void(Activity&)> on_completion;
99
100   void vetoable_start()
101   {
102     state_ = State::STARTING;
103     if (dependencies_solved() && is_assigned()) {
104       XBT_CVERB(s4u_activity, "'%s' is assigned to a resource and all dependencies are solved. Let's start", get_cname());
105       start();
106     } else {
107       if (vetoed_activities_ != nullptr)
108         vetoed_activities_->insert(this);
109       on_veto(*this);
110     }
111   }
112
113   void complete(Activity::State state)
114   {
115     state_ = state;
116     if (state == State::FINISHED)
117       release_dependencies();
118     on_completion(*this);
119   }
120
121   static std::set<Activity*>* get_vetoed_activities() { return vetoed_activities_; }
122   static void set_vetoed_activities(std::set<Activity*>* whereto) { vetoed_activities_ = whereto; }
123
124 #ifndef DOXYGEN
125   Activity(Activity const&) = delete;
126   Activity& operator=(Activity const&) = delete;
127 #endif
128
129   /** Starts a previously created activity.
130    *
131    * This function is optional: you can call wait() even if you didn't call start()
132    */
133   virtual Activity* start() = 0;
134   /** Blocks the current actor until the activity is terminated */
135   Activity* wait() { return wait_for(-1.0); }
136   /** Blocks the current actor until the activity is terminated, or until the timeout is elapsed\n
137    *  Raises: timeout exception.*/
138   Activity* wait_for(double timeout);
139   /** Blocks the current actor until the activity is terminated, or until the time limit is reached\n
140    * Raises: timeout exception. */
141   void wait_until(double time_limit);
142
143   /** Cancel that activity */
144   Activity* cancel();
145   /** Retrieve the current state of the activity */
146   Activity::State get_state() const { return state_; }
147   /** Return a string representation of the activity's state (one of INITED, STARTING, STARTED, CANCELED, FINISHED) */
148   const char* get_state_str() const;
149   void set_state(Activity::State state) { state_ = state; }
150   /** Tests whether the given activity is terminated yet. */
151   virtual bool test();
152
153   /** Blocks the progression of this activity until it gets resumed */
154   virtual Activity* suspend();
155   /** Unblock the progression of this activity if it was suspended previously */
156   virtual Activity* resume();
157   /** Whether or not the progression of this activity is blocked */
158   bool is_suspended() const { return suspended_; }
159
160   virtual const char* get_cname() const       = 0;
161   virtual const std::string& get_name() const = 0;
162
163   /** Get the remaining amount of work that this Activity entails. When it's 0, it's done. */
164   virtual double get_remaining() const;
165   /** Set the [remaining] amount of work that this Activity will entail
166    *
167    * It is forbidden to change the amount of work once the Activity is started */
168   Activity* set_remaining(double remains);
169
170   double get_start_time() const;
171   double get_finish_time() const;
172   void mark() { marked_ = true; }
173   bool is_marked() const { return marked_; }
174
175   /** Returns the internal implementation of this Activity */
176   kernel::activity::ActivityImpl* get_impl() const { return pimpl_.get(); }
177
178 #ifndef DOXYGEN
179   friend void intrusive_ptr_release(Activity* a)
180   {
181     if (a->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
182       std::atomic_thread_fence(std::memory_order_acquire);
183       delete a;
184     }
185   }
186   friend void intrusive_ptr_add_ref(Activity* a) { a->refcount_.fetch_add(1, std::memory_order_relaxed); }
187 #endif
188   Activity* add_ref()
189   {
190     intrusive_ptr_add_ref(this);
191     return this;
192   }
193   void unref() { intrusive_ptr_release(this); }
194
195 private:
196   kernel::activity::ActivityImplPtr pimpl_ = nullptr;
197   Activity::State state_                   = Activity::State::INITED;
198   double remains_                          = 0;
199   bool suspended_                          = false;
200   bool marked_                             = false;
201   std::vector<ActivityPtr> successors_;
202   std::set<ActivityPtr> dependencies_;
203   std::atomic_int_fast32_t refcount_{0};
204 };
205
206 template <class AnyActivity> class Activity_T : public Activity {
207   std::string name_             = "unnamed";
208   std::string tracing_category_ = "";
209   void* user_data_              = nullptr;
210
211 public:
212   AnyActivity* add_successor(ActivityPtr a)
213   {
214     Activity::add_successor(a);
215     return static_cast<AnyActivity*>(this);
216   }
217   AnyActivity* remove_successor(ActivityPtr a)
218   {
219     Activity::remove_successor(a);
220     return static_cast<AnyActivity*>(this);
221   }
222   AnyActivity* set_name(const std::string& name)
223   {
224     xbt_assert(get_state() == State::INITED, "Cannot change the name of an activity after its start");
225     name_ = name;
226     return static_cast<AnyActivity*>(this);
227   }
228   const std::string& get_name() const override { return name_; }
229   const char* get_cname() const override { return name_.c_str(); }
230
231   AnyActivity* set_tracing_category(const std::string& category)
232   {
233     xbt_assert(get_state() == State::INITED, "Cannot change the tracing category of an activity after its start");
234     tracing_category_ = category;
235     return static_cast<AnyActivity*>(this);
236   }
237   const std::string& get_tracing_category() const { return tracing_category_; }
238
239   AnyActivity* set_user_data(void* data)
240   {
241     user_data_ = data;
242     return static_cast<AnyActivity*>(this);
243   }
244
245   void* get_user_data() const { return user_data_; }
246
247   AnyActivity* vetoable_start()
248   {
249     Activity::vetoable_start();
250     return static_cast<AnyActivity*>(this);
251   }
252
253   AnyActivity* cancel() { return static_cast<AnyActivity*>(Activity::cancel()); }
254   AnyActivity* wait() { return wait_for(-1.0); }
255   virtual AnyActivity* wait_for(double timeout) { return static_cast<AnyActivity*>(Activity::wait_for(timeout)); }
256
257 #ifndef DOXYGEN
258   /* The refcounting is done in the ancestor class, Activity, but we want each of the classes benefiting of the CRTP
259    * (Exec, Comm, etc) to have smart pointers too, so we define these methods here, that forward the ptr_release and
260    * add_ref to the Activity class. Hopefully, the "inline" helps to not hinder the perf here.
261    */
262   friend void inline intrusive_ptr_release(AnyActivity* a) { intrusive_ptr_release(static_cast<Activity*>(a)); }
263   friend void inline intrusive_ptr_add_ref(AnyActivity* a) { intrusive_ptr_add_ref(static_cast<Activity*>(a)); }
264 #endif
265 };
266
267 } // namespace s4u
268 } // namespace simgrid
269
270 #endif /* SIMGRID_S4U_ACTIVITY_HPP */