Debian Codegraph @

src/later.cpp

raw symbols SCIP
1 #include "later.h"
2 #include <Rcpp.h>
3 #include <queue>
4 #include <memory>
5 #include "debug.h"
6 #include "utils.h"
7 #include "threadutils.h"
8
9 #include "callback_registry.h"
10 #include "callback_registry_table.h"
11
12 #include "interrupt.h"
13
14 using std::shared_ptr;
15
16 static size_t exec_callbacks_reentrancy_count = 0;
17
18 // instance has global scope as declared in callback_registry_table.h
19 CallbackRegistryTable callbackRegistryTable;
20
21
22 class ProtectCallbacks {
23 public:
24 ProtectCallbacks() {
25 exec_callbacks_reentrancy_count++;
26 }
27 ~ProtectCallbacks() {
28 exec_callbacks_reentrancy_count--;
29 }
30 };
31
32 // Returns number of frames on the call stack. Basically just a wrapper for
33 // base::sys.nframe(). Note that this can report that an error occurred if the
34 // user sends an interrupt while the `sys.nframe()` function is running. I
35 // believe that the only reason that it should set errorOccurred is because of
36 // a user interrupt.
37 int sys_nframe() {
38 ASSERT_MAIN_THREAD()
39 SEXP e, result;
40 int errorOccurred, value;
41
42 BEGIN_SUSPEND_INTERRUPTS {
43 PROTECT(e = Rf_lang1(Rf_install("sys.nframe")));
44 PROTECT(result = R_tryEval(e, R_BaseEnv, &errorOccurred));
45
46 if (errorOccurred) {
47 value = -1;
48 } else {
49 value = INTEGER(result)[0];
50 }
51
52 UNPROTECT(2);
53 } END_SUSPEND_INTERRUPTS;
54
55 return value;
56 }
57
58 // Returns true if execCallbacks is executing, or sys.nframes() returns 0.
59 bool at_top_level() {
60 ASSERT_MAIN_THREAD()
61 if (exec_callbacks_reentrancy_count != 0)
62 return false;
63
64 int nframe = sys_nframe();
65 if (nframe == -1) {
66 Rcpp::stop("Error occurred while calling sys.nframe()");
67 }
68 return nframe == 0;
69 }
70
71 // ============================================================================
72 // Current registry/event loop
73 // ============================================================================
74 //
75 // In the R code, the term "loop" is used. In the C++ code, the terms "loop"
76 // and "registry" are both used. "Loop" is usually used when interfacing with
77 // R-facing event loop, and "registry" is usually used when interfacing with
78 // the implementation, which uses a callback registry.
79 //
80 // The current registry is kept track of entirely in C++, and not in R
81 // (although it can be queried from R). This is because when running a loop
82 // with children, it sets the current loop as it runs each of the children,
83 // and to do so in R would require calling back into R for each child, which
84 // would impose more overhead.
85
86 static int current_registry;
87
88 // [[Rcpp::export(rng = false)]]
89 void setCurrentRegistryId(int id) {
90 ASSERT_MAIN_THREAD()
91 current_registry = id;
92 }
93
94 // [[Rcpp::export(rng = false)]]
95 int getCurrentRegistryId() {
96 ASSERT_MAIN_THREAD()
97 return current_registry;
98 }
99
100 // Class for setting current registry and resetting when function exits, using
101 // RAII.
102 class CurrentRegistryGuard {
103 public:
104 CurrentRegistryGuard(int id) {
105 ASSERT_MAIN_THREAD()
106 old_id = getCurrentRegistryId();
107 setCurrentRegistryId(id);
108 }
109 ~CurrentRegistryGuard() {
110 setCurrentRegistryId(old_id);
111 }
112 private:
113 int old_id;
114 };
115
116
117 // ============================================================================
118 // Callback registry functions
119 // ============================================================================
120
121 shared_ptr<CallbackRegistry> getGlobalRegistry() {
122 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(GLOBAL_LOOP);
123 if (registry == nullptr) {
124 (Rf_error)("Global registry does not exist.");
125 }
126 return registry;
127 }
128
129 // This deletes a CallbackRegistry and deregisters it as a child of its
130 // parent. Any children of this registry are orphaned -- they no longer have a
131 // parent. (Maybe this should be an option?)
132 //
133 // [[Rcpp::export(rng = false)]]
134 bool deleteCallbackRegistry(int loop_id) {
135 ASSERT_MAIN_THREAD()
136 if (loop_id == GLOBAL_LOOP) {
137 Rcpp::stop("Can't destroy global loop.");
138 }
139 if (loop_id == getCurrentRegistryId()) {
140 Rcpp::stop("Can't destroy current loop.");
141 }
142
143 return callbackRegistryTable.remove(loop_id);
144 }
145
146
147 // This is called when the R loop handle is GC'd.
148 // [[Rcpp::export(rng = false)]]
149 bool notifyRRefDeleted(int loop_id) {
150 ASSERT_MAIN_THREAD()
151 if (loop_id == GLOBAL_LOOP) {
152 Rcpp::stop("Can't notify that reference to global loop is deleted.");
153 }
154 if (loop_id == getCurrentRegistryId()) {
155 Rcpp::stop("Can't notify that reference to current loop is deleted.");
156 }
157
158 return callbackRegistryTable.notifyRRefDeleted(loop_id);
159 }
160
161
162 // [[Rcpp::export(rng = false)]]
163 void createCallbackRegistry(int id, int parent_id) {
164 ASSERT_MAIN_THREAD()
165 callbackRegistryTable.create(id, parent_id);
166 }
167
168 // [[Rcpp::export(rng = false)]]
169 bool existsCallbackRegistry(int id) {
170 ASSERT_MAIN_THREAD()
171 return callbackRegistryTable.exists(id);
172 }
173
174 // [[Rcpp::export(rng = false)]]
175 Rcpp::List list_queue_(int id) {
176 ASSERT_MAIN_THREAD()
177 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(id);
178 if (registry == nullptr) {
179 Rcpp::stop("CallbackRegistry does not exist.");
180 }
181 return registry->list();
182 }
183
184
185 // Execute callbacks for a single event loop.
186 bool execCallbacksOne(
187 bool runAll,
188 shared_ptr<CallbackRegistry> callback_registry,
189 Timestamp now
190 ) {
191 ASSERT_MAIN_THREAD()
192 // execCallbacks can be called directly from C code, and the callbacks may
193 // include Rcpp code. (Should we also call wrap?)
194 Rcpp::RNGScope rngscope;
195 ProtectCallbacks pcscope;
196
197 // Set current loop for the duration of this function.
198 CurrentRegistryGuard current_registry_guard(callback_registry->getId());
199
200 do {
201 // We only take one at a time, because we don't want to lose callbacks if
202 // one of the callbacks throws an error
203 Callback_sp callback = callback_registry->pop(now);
204 if (callback == nullptr) {
205 break;
206 }
207
208 // This line may throw errors!
209 callback->invoke();
210
211 } while (runAll);
212
213 // I think there's no need to lock this since it's only modified from the
214 // main thread. But need to check.
215 std::vector<std::shared_ptr<CallbackRegistry> > children = callback_registry->children;
216 for (std::vector<std::shared_ptr<CallbackRegistry> >::iterator it = children.begin();
217 it != children.end();
218 ++it)
219 {
220 execCallbacksOne(true, *it, now);
221 }
222
223 return true;
224 }
225
226 // Execute callbacks for an event loop and its children.
227 // [[Rcpp::export(rng = false)]]
228 bool execCallbacks(double timeoutSecs, bool runAll, int loop_id) {
229 ASSERT_MAIN_THREAD()
230 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(loop_id);
231 if (registry == nullptr) {
232 Rcpp::stop("CallbackRegistry does not exist.");
233 }
234
235 if (!registry->wait(timeoutSecs, true)) {
236 return false;
237 }
238
239 Timestamp now;
240 execCallbacksOne(runAll, registry, now);
241
242 // Call this now, in case any CallbackRegistries which have no R references
243 // have emptied.
244 callbackRegistryTable.pruneRegistries();
245 return true;
246 }
247
248
249 // This function is called from the input handler on Unix, or the Windows
250 // equivalent. It may throw exceptions.
251 //
252 // Invoke execCallbacks up to 20 times. At the first iteration where no work is
253 // done, terminate. We call this from the top level instead of just calling
254 // execCallbacks because the top level only gets called occasionally (every 10's
255 // of ms), so tasks that generate other tasks will execute surprisingly slowly.
256 //
257 // Example:
258 // promise_map(1:1000, function(i) {
259 // message(i)
260 // promise_resolve(i)
261 // })
262 bool execCallbacksForTopLevel() {
263 bool any = false;
264 for (size_t i = 0; i < 20; i++) {
265 if (!execCallbacks(0, true, GLOBAL_LOOP))
266 return any;
267 any = true;
268 }
269 return any;
270 }
271
272 // [[Rcpp::export(rng = false)]]
273 bool idle(int loop_id) {
274 ASSERT_MAIN_THREAD()
275 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(loop_id);
276 if (registry == nullptr) {
277 Rcpp::stop("CallbackRegistry does not exist.");
278 }
279 return registry->empty();
280 }
281
282
283 static bool initialized = false;
284 // [[Rcpp::export(rng = false)]]
285 void ensureInitialized() {
286 if (initialized) {
287 return;
288 }
289 REGISTER_MAIN_THREAD()
290
291 // Note that the global registry is not created here, but in R, from the
292 // .onLoad function.
293 setCurrentRegistryId(GLOBAL_LOOP);
294
295 // Call the platform-specific initialization for the mechanism that runs the
296 // event loop when the console is idle.
297 ensureAutorunnerInitialized();
298 initialized = true;
299 }
300
301 // [[Rcpp::export(rng = false)]]
302 std::string execLater(Rcpp::Function callback, double delaySecs, int loop_id) {
303 ASSERT_MAIN_THREAD()
304 ensureInitialized();
305 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(loop_id);
306 if (registry == nullptr) {
307 Rcpp::stop("CallbackRegistry does not exist.");
308 }
309 uint64_t callback_id = doExecLater(registry, callback, delaySecs, true);
310
311 // We have to convert it to a string in order to maintain 64-bit precision,
312 // since R doesn't support 64 bit integers.
313 return toString(callback_id);
314 }
315
316
317
318 bool cancel(uint64_t callback_id, int loop_id) {
319 ASSERT_MAIN_THREAD()
320 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(loop_id);
321 if (registry == nullptr) {
322 return false;
323 }
324 return registry->cancel(callback_id);
325 }
326
327 // [[Rcpp::export(rng = false)]]
328 bool cancel(std::string callback_id_s, int loop_id) {
329 ASSERT_MAIN_THREAD()
330 uint64_t callback_id;
331 std::istringstream iss(callback_id_s);
332 iss >> callback_id;
333
334 // If the input is good (just a number with no other text) then eof will be
335 // 1 and fail will be 0.
336 if (! (iss.eof() && !iss.fail())) {
337 return false;
338 }
339
340 return cancel(callback_id, loop_id);
341 }
342
343
344
345 // [[Rcpp::export(rng = false)]]
346 double nextOpSecs(int loop_id) {
347 ASSERT_MAIN_THREAD()
348 shared_ptr<CallbackRegistry> registry = callbackRegistryTable.getRegistry(loop_id);
349 if (registry == nullptr) {
350 Rcpp::stop("CallbackRegistry does not exist.");
351 }
352
353 Optional<Timestamp> nextTime = registry->nextTimestamp();
354 if (!nextTime.has_value()) {
355 return R_PosInf;
356 } else {
357 Timestamp now;
358 return nextTime->diff_secs(now);
359 }
360 }
361
362 // Schedules a C function to execute on a specific event loop. Returns
363 // callback ID on success, or 0 on error.
364 extern "C" uint64_t execLaterNative2(void (*func)(void*), void* data, double delaySecs, int loop_id) {
365 ensureInitialized();
366 return callbackRegistryTable.scheduleCallback(func, data, delaySecs, loop_id);
367 }
368
369 extern "C" int apiVersion() {
370 return LATER_DLL_API_VERSION;
371 }