Debian Codegraph @

inst/include/later_api.h

raw symbols SCIP
1 #ifndef _later_later_api_h
2 #define _later_later_api_h
3
4 // ---- Platform prerequisites ------------------------------------------------
5 // System and R headers required by the later API.
6
7 #ifndef R_NO_REMAP
8 #define R_NO_REMAP
9 #endif
10
11 #ifndef STRICT_R_HEADERS
12 #define STRICT_R_HEADERS
13 #endif
14
15 #ifdef _WIN32
16 #ifndef _WIN32_WINNT
17 #define _WIN32_WINNT 0x0600 // so R <= 4.1 can find WSAPoll() on Windows
18 #endif
19 #include <winsock2.h>
20 #define WIN32_LEAN_AND_MEAN
21 // Taken from http://tolstoy.newcastle.edu.au/R/e2/devel/06/11/1242.html
22 // Undefine the Realloc macro, which is defined by both R and by Windows stuff
23 #undef Realloc
24 // Also need to undefine the Free macro
25 #undef Free
26 #include <windows.h>
27 #else // _WIN32
28 #include <poll.h>
29 #include <pthread.h>
30 #endif // _WIN32
31
32 #include <Rinternals.h>
33
34 // ---- Public API ------------------------------------------------------------
35 // The later C++ interface. See the "Using later from C++" vignette for usage.
36
37 namespace later {
38
39 // This is the version of the later API provided by this file. Ideally, this
40 // should match the version of the API provided by the later DLL that is
41 // installed on the user's system. However, since this file is compiled into
42 // other packages (like httpuv and promises), it is possible that there will
43 // be a mismatch. In the future we will be able to compare at runtime it to
44 // the result from apiVersion(), with:
45 //
46 // int (*dll_api_version)() = (int (*)()) R_GetCCallable("later", "apiVersion");
47 // if (LATER_H_API_VERSION != (*dll_api_version)()) { ... }
48 #define LATER_H_API_VERSION 3
49 #define GLOBAL_LOOP 0
50
51
52 // Gets the version of the later API that's provided by the _actually installed_
53 // version of later.
54 // # nocov start
55 // tested by cpp-version-mismatch job on CI
56 static int apiVersionRuntime() {
57 int (*dll_api_version)(void) = (int (*)(void)) R_GetCCallable("later", "apiVersion");
58 return (*dll_api_version)();
59 }
60 // # nocov end
61
62 // ---- later() ---------------------------------------------------------------
63 // Schedule a C function to execute on the main R thread after a delay.
64 // Safe to call from any thread.
65
66 inline void later(void (*func)(void*), void* data, double secs, int loop_id) {
67 // This function works by retrieving the later::execLaterNative2 function
68 // pointer using R_GetCCallable the first time it's called (per compilation
69 // unit, since it's inline). execLaterNative2 is designed to be safe to call
70 // from any thread, but R_GetCCallable is only safe to call from R's main
71 // thread (otherwise you get stack imbalance warnings or worse). Therefore,
72 // we have to ensure that the first call to execLaterNative2 happens on the
73 // main thread. We accomplish this using the statically initialized
74 // LaterInitializer object at the end of this file.
75 //
76 // This file is named later_api.h instead of later.h because Rcpp treats
77 // $PACKAGE.h files specially by including them in RcppExports.cpp, and we
78 // definitely do not want the static initialization to happen there.
79
80 // The function type for the real execLaterNative2
81 typedef void (*elnfun)(void (*func)(void*), void*, double, int);
82 static elnfun eln = NULL;
83 if (!eln) {
84 // Initialize if necessary
85 if (func) {
86 // We're not initialized but someone's trying to actually schedule
87 // some code to be executed!
88 REprintf(
89 "Warning: later::execLaterNative2 called in uninitialized state.\n"
90 );
91 }
92 eln = (elnfun)R_GetCCallable("later", "execLaterNative2");
93 }
94
95 // We didn't want to execute anything, just initialize
96 if (!func) {
97 return;
98 }
99
100 eln(func, data, secs, loop_id);
101 }
102
103 inline void later(void (*func)(void*), void* data, double secs) {
104 later(func, data, secs, GLOBAL_LOOP);
105 }
106
107 // ---- later_fd() ------------------------------------------------------------
108 // Schedule a C function with file descriptor polling. Safe to call from any
109 // thread. Requires later >= 1.4.1 (API version 3).
110
111 // # nocov start
112 // tested by cpp-version-mismatch job on CI
113 static void later_fd_version_error(void (*func)(int *, void *), void *data, int num_fds, struct pollfd *fds, double secs, int loop_id) {
114 (void) func; (void) data; (void) num_fds; (void) fds; (void) secs; (void) loop_id;
115 (Rf_error)("later_fd called, but installed version of the 'later' package is too old; please upgrade 'later' to 1.4.1 or above");
116 }
117 // # nocov end
118
119 inline void later_fd(void (*func)(int *, void *), void *data, int num_fds, struct pollfd *fds, double secs, int loop_id) {
120 // See above note for later()
121
122 // The function type for the real execLaterFdNative
123 typedef void (*elfdnfun)(void (*)(int *, void *), void *, int, struct pollfd *, double, int);
124 static elfdnfun elfdn = NULL;
125 if (!elfdn) {
126 // Initialize if necessary
127 if (func) {
128 // We're not initialized but someone's trying to actually schedule
129 // some code to be executed!
130 REprintf(
131 "Warning: later::execLaterFdNative called in uninitialized state.\n"
132 );
133 }
134 if (apiVersionRuntime() >= 3) {
135 // Only later API version 3 supports execLaterFdNative
136 elfdn = (elfdnfun) R_GetCCallable("later", "execLaterFdNative");
137 } else {
138 // The installed version is too old and doesn't offer execLaterFdNative.
139 elfdn = later_fd_version_error;
140 }
141 }
142
143 // We didn't want to execute anything, just initialize
144 if (!func) {
145 return;
146 }
147
148 elfdn(func, data, num_fds, fds, secs, loop_id);
149 }
150
151 inline void later_fd(void (*func)(int *, void *), void *data, int num_fds, struct pollfd *fds, double secs) {
152 later_fd(func, data, num_fds, fds, secs, GLOBAL_LOOP);
153 }
154
155
156 // ---- BackgroundTask --------------------------------------------------------
157 // Helper class for running work on a background thread and returning results
158 // on the main R thread. Subclass and implement execute() and complete().
159
160 class BackgroundTask {
161
162 public:
163 BackgroundTask() {}
164 virtual ~BackgroundTask() {}
165
166 // Start executing the task
167 void begin() {
168 #ifndef _WIN32
169 pthread_attr_t attr;
170 pthread_attr_init(&attr);
171 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
172 pthread_t t;
173 pthread_create(&t, &attr, BackgroundTask::task_main, this);
174 pthread_attr_destroy(&attr);
175 #else
176 HANDLE hThread = ::CreateThread(
177 NULL, 0,
178 BackgroundTask::task_main_win,
179 this,
180 0,
181 NULL
182 );
183 ::CloseHandle(hThread);
184 #endif
185 }
186
187 protected:
188 // The task to be executed on the background thread.
189 // Neither the R runtime nor any R data structures may be
190 // touched from the background thread; any values that need
191 // to be passed into or out of the Execute method must be
192 // included as fields on the Task subclass object.
193 virtual void execute() = 0;
194
195 // A short task that runs on the main R thread after the
196 // background task has completed. It's safe to access the
197 // R runtime and R data structures from here.
198 virtual void complete() = 0;
199
200 private:
201 static void* task_main(void* data) {
202 BackgroundTask* task = reinterpret_cast<BackgroundTask*>(data);
203 // TODO: Error handling
204 task->execute();
205 later(&BackgroundTask::result_callback, task, 0);
206 return NULL;
207 }
208
209 #ifdef _WIN32
210 static DWORD WINAPI task_main_win(LPVOID lpParameter) {
211 task_main(lpParameter);
212 return 1;
213 }
214 #endif
215
216 static void result_callback(void* data) {
217 BackgroundTask* task = reinterpret_cast<BackgroundTask*>(data);
218 // TODO: Error handling
219 task->complete();
220 delete task;
221 }
222 };
223
224 } // namespace later
225
226 // ---- Static initialization -------------------------------------------------
227 // Ensures later() and later_fd() are initialized on the main R thread before
228 // any user code can call them from a background thread.
229
230 namespace {
231
232 class LaterInitializer {
233 public:
234 LaterInitializer() {
235 // See comment in later() to learn why we need to do this
236 // in a statically initialized object
237 later::later(NULL, NULL, 0);
238 later::later_fd(NULL, NULL, 0, NULL, 0);
239 }
240 };
241
242 static LaterInitializer init;
243
244 } // namespace
245
246 #endif