Debian Codegraph @

src/callback_registry.cpp

raw symbols SCIP
1 #include <atomic>
2 #include <functional>
3 #include <memory>
4 #include <vector>
5
6 #include "callback_registry.h"
7 #include "debug.h"
8
9 static std::atomic<uint64_t> nextCallbackId(1);
10
11 // ============================================================================
12 // StdFunctionCallback
13 // ============================================================================
14
15 StdFunctionCallback::StdFunctionCallback(Timestamp when, std::function<void(void)> func) :
16 Callback(when),
17 func(func)
18 {
19 this->callbackId = nextCallbackId++;
20 }
21
22 Rcpp::RObject StdFunctionCallback::rRepresentation() const {
23 using namespace Rcpp;
24 ASSERT_MAIN_THREAD()
25
26 return List::create(
27 _["id"] = callbackId,
28 _["when"] = when.diff_secs(Timestamp()),
29 _["callback"] = Rcpp::CharacterVector::create("C/C++ function")
30 );
31 }
32
33
34 // ============================================================================
35 // RcppFunctionCallback
36 // ============================================================================
37
38 RcppFunctionCallback::RcppFunctionCallback(Timestamp when, const Rcpp::Function& func) :
39 Callback(when),
40 func(func)
41 {
42 ASSERT_MAIN_THREAD()
43 this->callbackId = nextCallbackId++;
44 }
45
46 Rcpp::RObject RcppFunctionCallback::rRepresentation() const {
47 using namespace Rcpp;
48 ASSERT_MAIN_THREAD()
49
50 return List::create(
51 _["id"] = callbackId,
52 _["when"] = when.diff_secs(Timestamp()),
53 _["callback"] = func
54 );
55 }
56
57
58 // ============================================================================
59 // CallbackRegistry
60 // ============================================================================
61
62 // [[Rcpp::export(rng = false)]]
63 void testCallbackOrdering() {
64 std::vector<StdFunctionCallback> callbacks;
65 Timestamp ts;
66 std::function<void(void)> func;
67 for (size_t i = 0; i < 100; i++) {
68 callbacks.push_back(StdFunctionCallback(ts, func));
69 }
70 for (size_t i = 1; i < 100; i++) {
71 if (callbacks[i] < callbacks[i-1]) {
72 ::Rcpp::stop("Callback ordering is broken [1]");
73 }
74 if (!(callbacks[i] > callbacks[i-1])) {
75 ::Rcpp::stop("Callback ordering is broken [2]");
76 }
77 if (callbacks[i-1] > callbacks[i]) {
78 ::Rcpp::stop("Callback ordering is broken [3]");
79 }
80 if (!(callbacks[i-1] < callbacks[i])) {
81 ::Rcpp::stop("Callback ordering is broken [4]");
82 }
83 }
84 for (size_t i = 100; i > 1; i--) {
85 if (callbacks[i-1] < callbacks[i-2]) {
86 ::Rcpp::stop("Callback ordering is broken [2]");
87 }
88 }
89 }
90
91 CallbackRegistry::CallbackRegistry(int id, Mutex* mutex, ConditionVariable* condvar)
92 : id(id), mutex(mutex), condvar(condvar)
93 {
94 ASSERT_MAIN_THREAD()
95 }
96
97 CallbackRegistry::~CallbackRegistry() {
98 ASSERT_MAIN_THREAD()
99 }
100
101 int CallbackRegistry::getId() const {
102 return id;
103 }
104
105 uint64_t CallbackRegistry::add(const Rcpp::Function& func, double secs) {
106 // Copies of the Rcpp::Function should only be made on the main thread.
107 ASSERT_MAIN_THREAD()
108 Timestamp when(secs);
109 Callback_sp cb = std::make_shared<RcppFunctionCallback>(when, func);
110 Guard guard(mutex);
111 queue.insert(cb);
112 condvar->signal();
113
114 return cb->getCallbackId();
115 }
116
117 uint64_t CallbackRegistry::add(void (*func)(void*), void* data, double secs) {
118 Timestamp when(secs);
119 Callback_sp cb = std::make_shared<StdFunctionCallback>(when, std::bind(func, data));
120 Guard guard(mutex);
121 queue.insert(cb);
122 condvar->signal();
123
124 return cb->getCallbackId();
125 }
126
127 bool CallbackRegistry::cancel(uint64_t id) {
128 Guard guard(mutex);
129
130 cbSet::const_iterator it;
131 for (it = queue.begin(); it != queue.end(); ++it) {
132 if ((*it)->getCallbackId() == id) {
133 queue.erase(it);
134 return true;
135 }
136 }
137
138 return false;
139 }
140
141 // The smallest timestamp present in the registry, if any.
142 // Use this to determine the next time we need to pump events.
143 Optional<Timestamp> CallbackRegistry::nextTimestamp(bool recursive) const {
144 Guard guard(mutex);
145
146 Optional<Timestamp> minTimestamp;
147
148 if (! this->queue.empty()) {
149 cbSet::const_iterator it = queue.begin();
150 minTimestamp = Optional<Timestamp>((*it)->when);
151 }
152
153 // Now check children
154 if (recursive) {
155 for (std::vector<std::shared_ptr<CallbackRegistry> >::const_iterator it = children.begin();
156 it != children.end();
157 ++it)
158 {
159 Optional<Timestamp> childNextTimestamp = (*it)->nextTimestamp(recursive);
160
161 if (childNextTimestamp.has_value()) {
162 if (minTimestamp.has_value()) {
163 if (*childNextTimestamp < *minTimestamp) {
164 minTimestamp = childNextTimestamp;
165 }
166 } else {
167 minTimestamp = childNextTimestamp;
168 }
169 }
170 }
171 }
172
173 return minTimestamp;
174 }
175
176 bool CallbackRegistry::empty() const {
177 if (fd_waits.load() > 0) {
178 return false;
179 }
180 Guard guard(mutex);
181 return this->queue.empty();
182 }
183
184 // Returns true if the smallest timestamp exists and is not in the future.
185 bool CallbackRegistry::due(const Timestamp& time, bool recursive) const {
186 ASSERT_MAIN_THREAD()
187 Guard guard(mutex);
188 cbSet::const_iterator cbSet_it = queue.begin();
189 if (!this->queue.empty() && !((*cbSet_it)->when > time)) {
190 return true;
191 }
192
193 // Now check children
194 if (recursive) {
195 for (std::vector<std::shared_ptr<CallbackRegistry> >::const_iterator it = children.begin();
196 it != children.end();
197 ++it)
198 {
199 if ((*it)->due(time, true)) {
200 return true;
201 }
202 }
203 }
204
205 return false;
206 }
207
208 Callback_sp CallbackRegistry::pop(const Timestamp& time) {
209 ASSERT_MAIN_THREAD()
210 Guard guard(mutex);
211 Callback_sp result;
212 if (this->due(time, false)) {
213 cbSet::iterator it = queue.begin();
214 result = *it;
215 this->queue.erase(it);
216 }
217 return result;
218 }
219
220 bool CallbackRegistry::wait(double timeoutSecs, bool recursive) const {
221 ASSERT_MAIN_THREAD()
222 if (timeoutSecs == R_PosInf || timeoutSecs < 0) {
223 // "1000 years ought to be enough for anybody" --Bill Gates
224 timeoutSecs = 3e10;
225 }
226
227 Timestamp expireTime(timeoutSecs);
228
229 Guard guard(mutex);
230 while (true) {
231 Timestamp end = expireTime;
232 Optional<Timestamp> next = nextTimestamp(recursive);
233 if (next.has_value() && *next < expireTime) {
234 end = *next;
235 }
236 double waitFor = end.diff_secs(Timestamp());
237 if (waitFor <= 0)
238 break;
239 // Don't wait for more than 2 seconds at a time, in order to keep us
240 // at least somewhat responsive to user interrupts
241 if (waitFor > 2) {
242 waitFor = 2;
243 }
244 condvar->timedwait(waitFor);
245 Rcpp::checkUserInterrupt();
246 }
247
248 return due();
249 }
250
251
252 Rcpp::List CallbackRegistry::list() const {
253 ASSERT_MAIN_THREAD()
254 Guard guard(mutex);
255
256 Rcpp::List results;
257
258 cbSet::const_iterator it;
259
260 for (it = queue.begin(); it != queue.end(); it++) {
261 results.push_back((*it)->rRepresentation());
262 }
263
264 return results;
265 }
266
267 void CallbackRegistry::fd_waits_incr() {
268 ++fd_waits;
269 }
270
271 void CallbackRegistry::fd_waits_decr() {
272 --fd_waits;
273 }