Debian Codegraph @

src/later_posix.cpp

raw symbols SCIP
1 #ifndef _WIN32
2
3 #include <Rcpp.h>
4 #include <R_ext/eventloop.h>
5 #include <unistd.h>
6 #include <queue>
7
8 #include "later.h"
9 #include "callback_registry.h"
10 #include "timer_posix.h"
11 #include "threadutils.h"
12 #include "debug.h"
13
14 using namespace Rcpp;
15
16 #define LATER_ACTIVITY 20
17 #define LATER_DUMMY_ACTIVITY 21
18
19 extern void* R_GlobalContext;
20 extern void* R_TopLevelContext;
21
22 // Whether we have initialized the input handler.
23 static int initialized = 0;
24
25 // The handles to the read and write ends of a pipe. We use this pipe
26 // to signal R's input handler callback mechanism that we want to be
27 // called back.
28 static int pipe_in = -1;
29 static int pipe_out = -1;
30
31 static int dummy_pipe_in = -1;
32 static int dummy_pipe_out = -1;
33
34 // Whether the file descriptor is ready for reading, i.e., whether
35 // the input handler callback is scheduled to be called. We use this
36 // to avoid unnecessarily writing to the pipe.
37 static bool hot = false;
38 // This mutex protects reading/writing of `hot` and of reading from/writing to
39 // the pipe.
40 static Mutex m(tct_mtx_plain);
41
42 // The buffer we're using for the pipe. This doesn't have to be large,
43 // in theory it only ever holds zero or one byte.
44 static size_t BUF_SIZE = 256;
45 static void *buf;
46
47 void set_fd(bool ready) {
48 Guard g(&m);
49
50 if (ready != hot) {
51 if (ready) {
52 ssize_t cbytes = write(pipe_in, "a", 1);
53 (void)cbytes; // squelch compiler warning
54 hot = true;
55 } else {
56 if (read(pipe_out, buf, BUF_SIZE) < 0) {
57 Rf_warningcall_immediate(R_NilValue, "Failed to read out of pipe for later package");
58 }
59 hot = false;
60 }
61 }
62 }
63
64 namespace {
65 void fd_on() {
66 set_fd(true);
67 }
68
69 Timer timer(fd_on);
70 } // namespace
71
72 class ResetTimerOnExit {
73 public:
74 ResetTimerOnExit() {
75 }
76 ~ResetTimerOnExit() {
77 ASSERT_MAIN_THREAD()
78 // Find the next event in the registry and, if there is one, set the timer.
79 Optional<Timestamp> nextEvent = getGlobalRegistry()->nextTimestamp();
80 if (nextEvent.has_value()) {
81 timer.set(*nextEvent);
82 }
83 }
84 };
85
86 static void async_input_handler(void *data) {
87 ASSERT_MAIN_THREAD()
88 set_fd(false);
89
90 if (!at_top_level()) {
91 // It's not safe to run arbitrary callbacks when other R code
92 // is already running. Wait until we're back at the top level.
93
94 // jcheng 2017-08-02: We can't just leave the file descriptor hot and let
95 // async_input_handler get invoked as fast as possible. Previously we did
96 // this, but on POSIX systems, it interferes with R_SocketWait.
97 // https://github.com/r-lib/later/issues/4
98 // Instead, we set the file descriptor to cold, and tell the timer to fire
99 // again in a few milliseconds. This should give enough breathing room that
100 // we don't interfere with the sockets too much.
101 // shikokuchuo 2026-02-07: reduced to just one millisecond
102 timer.set(Timestamp(0.001));
103 return;
104 }
105
106 // jcheng 2017-08-01: While callbacks are executing, make the file descriptor
107 // not-ready so that our input handler is not even called back by R.
108 // Previously we'd let the input handler run but return quickly, but this
109 // seemed to cause R_SocketWait to hang (encountered while working with the
110 // future package, trying to call value(future) with plan(multisession)).
111 ResetTimerOnExit resetTimerOnExit_scope;
112
113 // This try-catch is meant to be similar to the BEGIN_RCPP and VOID_END_RCPP
114 // macros. They are needed for two reasons: first, if an exception occurs in
115 // any of the callbacks, destructors will still execute; and second, if an
116 // exception (including R-level error) occurs in a callback and it reaches
117 // the top level in an R input handler, R appears to be unable to handle it
118 // properly.
119 // https://github.com/r-lib/later/issues/12
120 // https://github.com/RcppCore/Rcpp/issues/753
121 // https://github.com/r-lib/later/issues/31
122 try {
123 execCallbacksForTopLevel();
124 }
125 catch(Rcpp::internal::InterruptedException &e) {
126 DEBUG_LOG("async_input_handler: caught Rcpp::internal::InterruptedException", LOG_INFO);
127 REprintf("later: interrupt occurred while executing callback.\n");
128 }
129 catch(Rcpp::LongjumpException& e){
130 DEBUG_LOG("async_input_handler: caught exception", LOG_INFO);
131 REprintf("later: exception occurred while executing callback.\n");
132 }
133 catch(std::exception& e){
134 DEBUG_LOG("async_input_handler: caught exception", LOG_INFO);
135 std::string msg = "later: exception occurred while executing callback: \n";
136 msg += e.what();
137 msg += "\n";
138 REprintf("%s", msg.c_str());
139 }
140 catch( ... ){
141 REprintf("later: c++ exception (unknown reason) occurred while executing callback.\n");
142 }
143 }
144
145 static InputHandler* inputHandlerHandle;
146 static InputHandler* dummyInputHandlerHandle;
147
148 // If the real input handler has been removed, the dummy input handler removes
149 // itself. The real input handler cannot remove both; otherwise a segfault
150 // could occur.
151 static void remove_dummy_handler(void *data) {
152 ASSERT_MAIN_THREAD()
153 removeInputHandler(&R_InputHandlers, dummyInputHandlerHandle);
154 if (dummy_pipe_in > 0) {
155 close(dummy_pipe_in);
156 dummy_pipe_in = -1;
157 }
158 if (dummy_pipe_out > 0) {
159 close(dummy_pipe_out);
160 dummy_pipe_out = -1;
161 }
162 }
163
164 // Callback to run in child process after forking.
165 void child_proc_after_fork() {
166 ASSERT_MAIN_THREAD()
167 if (initialized) {
168 removeInputHandler(&R_InputHandlers, inputHandlerHandle);
169
170 if (pipe_in > 0) {
171 close(pipe_in);
172 pipe_in = -1;
173 }
174 if (pipe_out > 0) {
175 close(pipe_out);
176 pipe_out = -1;
177 }
178
179 removeInputHandler(&R_InputHandlers, dummyInputHandlerHandle);
180 if (dummy_pipe_in > 0) {
181 close(dummy_pipe_in);
182 dummy_pipe_in = -1;
183 }
184 if (dummy_pipe_out > 0) {
185 close(dummy_pipe_out);
186 dummy_pipe_out = -1;
187 }
188
189 initialized = 0;
190 }
191 }
192
193 void ensureAutorunnerInitialized() {
194 if (!initialized) {
195 buf = malloc(BUF_SIZE);
196
197 int pipes[2];
198 if (pipe(pipes)) {
199 free(buf);
200 Rcpp::stop("Failed to create pipe");
201 return;
202 }
203 pipe_out = pipes[0];
204 pipe_in = pipes[1];
205
206 inputHandlerHandle = addInputHandler(R_InputHandlers, pipe_out, async_input_handler, LATER_ACTIVITY);
207
208 // If the R process is forked, make sure that the child process doesn't mess
209 // with the pipes. This also means that functions scheduled in the child
210 // process with `later()` will only work if `run_now()` is called. In this
211 // situation, there's also the danger that a function will be scheduled by
212 // the parent process and then will be executed in the child process (in
213 // addition to in the parent process).
214 // https://github.com/r-lib/later/issues/140
215 pthread_atfork(NULL, NULL, child_proc_after_fork);
216
217 // Need to add a dummy input handler to avoid segfault when the "real"
218 // input handler removes the subsequent input handler in the linked list.
219 // See https://github.com/rstudio/httpuv/issues/78
220 int dummy_pipes[2];
221 if (pipe(dummy_pipes)) {
222 Rcpp::stop("Failed to create pipe");
223 return;
224 }
225 dummy_pipe_out = dummy_pipes[0];
226 dummy_pipe_in = dummy_pipes[1];
227 dummyInputHandlerHandle = addInputHandler(R_InputHandlers, dummy_pipe_out, remove_dummy_handler, LATER_DUMMY_ACTIVITY);
228
229 initialized = 1;
230 }
231 }
232
233 void deInitialize() {
234 ASSERT_MAIN_THREAD()
235 if (initialized) {
236 removeInputHandler(&R_InputHandlers, inputHandlerHandle);
237 if (pipe_in > 0) {
238 close(pipe_in);
239 pipe_in = -1;
240 }
241 if (pipe_out > 0) {
242 close(pipe_out);
243 pipe_out = -1;
244 }
245 initialized = 0;
246
247 // Trigger remove_dummy_handler()
248 // Store `ret` because otherwise it raises a significant warning.
249 ssize_t ret = write(dummy_pipe_in, "a", 1);
250 (void)ret; // squelch compiler warning
251 }
252 }
253
254 uint64_t doExecLater(std::shared_ptr<CallbackRegistry> callbackRegistry, Rcpp::Function callback, double delaySecs, bool resetTimer) {
255 ASSERT_MAIN_THREAD()
256 uint64_t callback_id = callbackRegistry->add(callback, delaySecs);
257
258 // The timer needs to be reset only if we're using the global loop, because
259 // this usage of the timer is relevant only when the event loop is driven by
260 // R's input handler (at the idle console), and only the global loop is by
261 // that.
262 if (resetTimer)
263 timer.set(*(callbackRegistry->nextTimestamp()));
264
265 return callback_id;
266 }
267
268 uint64_t doExecLater(std::shared_ptr<CallbackRegistry> callbackRegistry, void (*callback)(void*), void* data, double delaySecs, bool resetTimer) {
269 uint64_t callback_id = callbackRegistry->add(callback, data, delaySecs);
270
271 if (resetTimer)
272 timer.set(*(callbackRegistry->nextTimestamp()));
273
274 return callback_id;
275 }
276
277 #endif // ifndef _WIN32