Logo AND Algorithmique Numérique Distribuée

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