Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Factor Activity::wait() and wait_for() through CRTP.
[simgrid.git] / src / s4u / s4u_Activity.cpp
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 #include "xbt/log.h"
7
8 #include "simgrid/s4u/Activity.hpp"
9 #include "simgrid/s4u/Engine.hpp"
10 #include "src/kernel/activity/ActivityImpl.hpp"
11 #include "src/kernel/actor/ActorImpl.hpp"
12
13 XBT_LOG_EXTERNAL_CATEGORY(s4u);
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_activity, s4u, "S4U activities");
15
16 namespace simgrid {
17 namespace s4u {
18
19 void Activity::wait_until(double time_limit)
20 {
21   double now = Engine::get_clock();
22   if (time_limit > now)
23     wait_for(time_limit - now);
24 }
25
26 Activity* Activity::wait_for(double timeout)
27 {
28   if (state_ == State::INITED)
29     vetoable_start();
30
31   kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
32   kernel::actor::simcall_blocking([this, issuer, timeout] { this->get_impl()->wait_for(issuer, timeout); });
33   complete(State::FINISHED);
34   return this;
35 }
36
37 bool Activity::test()
38 {
39   xbt_assert(state_ == State::INITED || state_ == State::STARTED || state_ == State::STARTING ||
40              state_ == State::CANCELED || state_ == State::FINISHED);
41
42   if (state_ == State::CANCELED || state_ == State::FINISHED)
43     return true;
44
45   if (state_ == State::INITED || state_ == State::STARTING)
46     this->vetoable_start();
47
48   if (kernel::actor::simcall([this] { return this->get_impl()->test(); })) {
49     complete(State::FINISHED);
50     return true;
51   }
52
53   return false;
54 }
55
56 Activity* Activity::cancel()
57 {
58   kernel::actor::simcall([this] { pimpl_->cancel(); });
59   complete(State::CANCELED);
60   return this;
61 }
62
63 Activity* Activity::suspend()
64 {
65   if (suspended_)
66     return this; // Already suspended
67   suspended_ = true;
68
69   if (state_ == State::STARTED)
70     pimpl_->suspend();
71
72   return this;
73 }
74
75 Activity* Activity::resume()
76 {
77   if (not suspended_)
78     return this; // nothing to restore when it's not suspended
79
80   if (state_ == State::STARTED)
81     pimpl_->resume();
82
83   return this;
84 }
85
86 const char* Activity::get_state_str() const
87 {
88   return to_c_str(state_);
89 }
90
91 double Activity::get_remaining() const
92 {
93   if (state_ == State::INITED || state_ == State::STARTING)
94     return remains_;
95   else
96     return pimpl_->get_remaining();
97 }
98
99 Activity* Activity::set_remaining(double remains)
100 {
101   xbt_assert(state_ == State::INITED, "Cannot change the remaining amount of work once the Activity is started");
102   remains_ = remains;
103   return this;
104 }
105
106 } // namespace s4u
107 } // namespace simgrid