Debian Codegraph @

src/dex-scheduler.c

raw symbols SCIP
1 /*
2 * dex-scheduler.c
3 *
4 * Copyright 2022 Christian Hergert <[email protected]>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this library; if not, see <http://www.gnu.org/licenses/>.
18 *
19 * SPDX-License-Identifier: LGPL-2.1-or-later
20 */
21
22 #include "config.h"
23
24 #include <gio/gio.h>
25 #include <gobject/gvaluecollector.h>
26
27 #include "dex-aio-backend-private.h"
28 #include "dex-closure.h"
29 #include "dex-coroutine-private.h"
30 #include "dex-error.h"
31 #include "dex-fiber-private.h"
32 #include "dex-scheduler-private.h"
33 #include "dex-thread-storage-private.h"
34
35 /**
36 * DexScheduler:
37 *
38 * `DexScheduler` is the base class used by schedulers.
39 *
40 * Schedulers are responsible for ensuring asynchronous IO requests and
41 * completions are processed. They also schedule closures to be run as part
42 * of future result propagation. Additionally, they manage [[email protected]]
43 * execution and suspension.
44 *
45 * Specialized schedulers such as [[email protected]] will do this
46 * for a number of threads and dispatch new work between them.
47 */
48
49 static DexScheduler *default_scheduler;
50
51 DEX_DEFINE_ABSTRACT_TYPE (DexScheduler, dex_scheduler, DEX_TYPE_OBJECT)
52
53 #undef DEX_TYPE_SCHEDULER
54 #define DEX_TYPE_SCHEDULER dex_scheduler_type
55
56 static void
57 dex_scheduler_class_init (DexSchedulerClass *scheduler_class)
58 {
59 }
60
61 static void
62 dex_scheduler_init (DexScheduler *scheduler)
63 {
64 }
65
66 /**
67 * dex_scheduler_get_default:
68 *
69 * Gets the default scheduler for the process.
70 *
71 * The default scheduler executes tasks within the default
72 * [[email protected]]. Typically that is the main thread of the
73 * application.
74 *
75 * Returns: (transfer none) (not nullable): a [[email protected]]
76 */
77 DexScheduler *
78 dex_scheduler_get_default (void)
79 {
80 return default_scheduler;
81 }
82
83 void
84 dex_scheduler_set_default (DexScheduler *scheduler)
85 {
86 g_return_if_fail (default_scheduler == NULL);
87 g_return_if_fail (scheduler != NULL);
88
89 default_scheduler = scheduler;
90 }
91
92 /**
93 * dex_scheduler_get_thread_default:
94 *
95 * Gets the default scheduler for the thread.
96 *
97 * Returns: (transfer none) (nullable): a [[email protected]] or %NULL
98 */
99 DexScheduler *
100 dex_scheduler_get_thread_default (void)
101 {
102 return dex_thread_storage_get ()->scheduler;
103 }
104
105 void
106 dex_scheduler_set_thread_default (DexScheduler *scheduler)
107 {
108 dex_thread_storage_get ()->scheduler = scheduler;
109 }
110
111 /**
112 * dex_scheduler_ref_thread_default:
113 *
114 * Gets the thread default scheduler with the reference count incremented.
115 *
116 * Returns: (transfer full) (nullable): a [[email protected]] or %NULL
117 */
118 DexScheduler *
119 dex_scheduler_ref_thread_default (void)
120 {
121 DexScheduler *scheduler = dex_scheduler_get_thread_default ();
122
123 if (scheduler != NULL)
124 return dex_ref (scheduler);
125
126 return NULL;
127 }
128
129 /**
130 * dex_scheduler_push:
131 * @scheduler: a [[email protected]]
132 * @func: (scope async): the function callback
133 * @func_data: the closure data for @func
134 *
135 * Queues @func to run on @scheduler.
136 */
137 void
138 dex_scheduler_push (DexScheduler *scheduler,
139 DexSchedulerFunc func,
140 gpointer func_data)
141 {
142 g_return_if_fail (DEX_IS_SCHEDULER (scheduler));
143 g_return_if_fail (func != NULL);
144
145 DEX_SCHEDULER_GET_CLASS (scheduler)->push (scheduler, (DexWorkItem) {func, func_data});
146 }
147
148 /**
149 * dex_scheduler_get_main_context:
150 * @scheduler: a [[email protected]]
151 *
152 * Gets the default main context for a scheduler.
153 *
154 * This may be a different value depending on the calling thread.
155 *
156 * For example, calling this on the [[email protected]] from
157 * outside a worker thread may result in getting a shared
158 * [[email protected]] for the process.
159 *
160 * However, calling from a worker thread may give you a [[email protected]]
161 * specifically for that thread.
162 *
163 * Returns: (transfer none): a [[email protected]]
164 */
165 GMainContext *
166 dex_scheduler_get_main_context (DexScheduler *scheduler)
167 {
168 return DEX_SCHEDULER_GET_CLASS (scheduler)->get_main_context (scheduler);
169 }
170
171 /**
172 * dex_scheduler_get_aio_context: (skip)
173 * @scheduler: a [[email protected]]
174 *
175 * Gets a `DexAioContext` for the scheduler.
176 *
177 * This context can be used to execute asyncronous operations within the
178 * context of the scheduler. Generally this is done using asynchronous
179 * operations and submission/completions managed by the threads scheduler.
180 *
181 * Stability: Private
182 */
183 DexAioContext *
184 dex_scheduler_get_aio_context (DexScheduler *scheduler)
185 {
186 return DEX_SCHEDULER_GET_CLASS (scheduler)->get_aio_context (scheduler);
187 }
188
189 /**
190 * dex_scheduler_spawn:
191 * @scheduler: (nullable): a [[email protected]]
192 * @stack_size: stack size in bytes or 0
193 * @func: (scope notified) (closure func_data) (destroy func_data_destroy): a [[email protected]]
194 * @func_data: closure data for @func
195 * @func_data_destroy: closure notify for @func_data
196 *
197 * Request @scheduler to spawn a [[email protected]].
198 *
199 * The fiber will have its own stack and cooperatively schedules among other
200 * fibers sharing the scheduler.
201 *
202 * This can be called from any thread. The resulting fiber runs on the thread
203 * associated with the @scheduler.
204 *
205 * If @stack_size is 0, it will set to a sensible default. Otherwise, it is
206 * rounded up to the nearest page size.
207 *
208 * ```c
209 * static DexFuture *
210 * fiber_func (gpointer data)
211 * {
212 * GInputStream *stream = data;
213 * GError *error = NULL;
214 * GBytes *bytes = NULL;
215 *
216 * if (!(bytes = dex_await_boxed (dex_input_stream_read_bytes (stream, 4096, 0), &error)))
217 * return dex_future_new_for_error (error);
218 *
219 * ...
220 *
221 * return dex_future_new_true ();
222 * }
223 *
224 * DexFuture *
225 * spawn_fiber (GInputStream *stream)
226 * {
227 * return dex_scheduler_spawn (NULL, 0, fiber_func,
228 * g_object_ref (stream),
229 * g_object_unref);
230 * }
231 * ```
232 *
233 * Returns: (transfer full): a [[email protected]] that will resolve or reject when
234 * @func completes (or its resulting `DexFuture` completes).
235 */
236 DexFuture *
237 (dex_scheduler_spawn) (DexScheduler *scheduler,
238 gsize stack_size,
239 DexFiberFunc func,
240 gpointer func_data,
241 GDestroyNotify func_data_destroy)
242 {
243 DexFiber *fiber;
244
245 dex_return_error_if_fail (!scheduler || DEX_IS_SCHEDULER (scheduler));
246 dex_return_error_if_fail (func != NULL);
247
248 if (scheduler == NULL)
249 scheduler = dex_scheduler_get_default ();
250
251 dex_return_error_if_fail (scheduler != NULL);
252 dex_return_error_if_fail (DEX_SCHEDULER_GET_CLASS (scheduler)->spawn != NULL);
253
254 fiber = dex_fiber_new (func, func_data, func_data_destroy, stack_size);
255 DEX_SCHEDULER_GET_CLASS (scheduler)->spawn (scheduler, fiber);
256 return DEX_FUTURE (fiber);
257 }
258
259 /**
260 * dex_scheduler_spawn_coroutine:
261 * @scheduler: (nullable): a [[email protected]]
262 * @func: (scope notified): coroutine entrypoint
263 * @user_data: (transfer none): user data passed to the coroutine entrypoint
264 * @user_data_destroy: destroy notify for @user_data
265 *
266 * Request @scheduler to spawn a [[email protected]] and execute
267 * @func with user data.
268 *
269 * If the function returns %NULL while suspended, it should have set an awaited
270 * future in its context using one of the `DEX_COROUTINE_SUSPEND_*` helpers.
271 *
272 * Returns: (transfer full): a [[email protected]] that will resolve or reject
273 * when @func finishes or returns an error.
274 *
275 * Since: 1.2
276 */
277 DexFuture *
278 (dex_scheduler_spawn_coroutine) (DexScheduler *scheduler,
279 DexCoroutineFunc func,
280 gpointer user_data,
281 GDestroyNotify user_data_destroy)
282 {
283 DexCoroutine *coroutine;
284
285 dex_return_error_if_fail (!scheduler || DEX_IS_SCHEDULER (scheduler));
286 dex_return_error_if_fail (func != NULL);
287 if (scheduler == NULL)
288 scheduler = dex_scheduler_get_default ();
289
290 dex_return_error_if_fail (scheduler != NULL);
291 dex_return_error_if_fail (DEX_SCHEDULER_GET_CLASS (scheduler)->spawn_coroutine != NULL);
292
293 coroutine = dex_coroutine_new (func, user_data, user_data_destroy);
294 DEX_SCHEDULER_GET_CLASS (scheduler)->spawn_coroutine (scheduler, coroutine);
295
296 return DEX_FUTURE (coroutine);
297 }
298
299 DEX_DEFINE_CLOSURE_TYPE (DexSchedulerSpawnTrampoline, dex_scheduler_spawn_trampoline,
300 DEX_DEFINE_CLOSURE_VALUE (GCallback, callback),
301 DEX_DEFINE_CLOSURE_POINTER (GArray *, values, g_array_unref))
302
303 static inline DexFuture *
304 dex_scheduler_spawn_trampoline_fiber (gpointer data)
305 {
306 DexSchedulerSpawnTrampoline *state = data;
307 GClosure *closure = NULL;
308 GValue return_value = G_VALUE_INIT;
309 gpointer res;
310
311 g_assert (state != NULL);
312 g_assert (state->callback != NULL);
313 g_assert (state->values != NULL);
314
315 g_value_init (&return_value, G_TYPE_POINTER);
316 closure = g_cclosure_new (state->callback, NULL, NULL);
317 g_closure_set_marshal (closure, g_cclosure_marshal_generic);
318 g_closure_invoke (closure,
319 &return_value,
320 state->values->len,
321 (const GValue *)(gpointer)state->values->data,
322 NULL);
323 res = g_value_get_pointer (&return_value);
324
325 g_closure_unref (closure);
326 g_value_unset (&return_value);
327
328 return res;
329 }
330
331 /**
332 * dex_scheduler_spawnv: (skip)
333 * @scheduler: (nullable): a [[email protected]]
334 * @stack_size: stack size in bytes or 0
335 * @callback: the fiber to spawn
336 * @n_params: number of arguments of the fiber
337 * @...: arguments, pairs of #GType followed by the value
338 *
339 * Same as dex_scheduler_spawn() but trampolines into a fiber without having to
340 * create special structures on the way there.
341 *
342 * ```c
343 * static DexFuture *
344 * fiber_func (GInputStream *stream,
345 * int num)
346 * {
347 * ...
348 *
349 * return dex_future_new_true ();
350 * }
351 *
352 * DexFuture *
353 * spawn_fiber (GInputStream *stream)
354 * {
355 * return dex_scheduler_spawnv (NULL, 0,
356 * G_CALLBACK (fiber_func),
357 * 2,
358 * G_TYPE_POINTER, stream,
359 * G_TYPE_INT, 42);
360 * }
361 * ```
362 *
363 * Returns: (transfer full): a [[email protected]] that will resolve or reject when
364 * @callback completes (or its resulting `DexFuture` completes).
365 */
366 DexFuture *
367 dex_scheduler_spawnv (DexScheduler *scheduler,
368 gsize stack_size,
369 GCallback callback,
370 guint n_params,
371 ...)
372 {
373 DexSchedulerSpawnTrampoline *state;
374 char *errmsg = NULL;
375 GArray *values = NULL;
376 DexFuture *future;
377 va_list args;
378
379 values = g_array_new (FALSE, TRUE, sizeof (GValue));
380 g_array_set_clear_func (values, (GDestroyNotify)g_value_unset);
381 g_array_set_size (values, n_params);
382
383 va_start (args, n_params);
384
385 for (guint i = 0; i < n_params; i++)
386 {
387 GType gtype = va_arg (args, GType);
388 GValue *dest = &g_array_index (values, GValue, i);
389 GValue value = G_VALUE_INIT;
390
391 G_VALUE_COLLECT_INIT (&value, gtype, args, 0, &errmsg);
392
393 if (errmsg != NULL)
394 break;
395
396 g_value_init (dest, gtype);
397 g_value_copy (&value, dest);
398 g_value_unset (&value);
399 }
400
401 va_end (args);
402
403 if (errmsg != NULL)
404 {
405 future = dex_future_new_reject (DEX_ERROR,
406 DEX_ERROR_TYPE_MISMATCH,
407 "Failed to trampoline to fiber: %s",
408 errmsg);
409 }
410 else
411 {
412 state = dex_scheduler_spawn_trampoline_new ();
413 state->values = g_steal_pointer (&values);
414 state->callback = callback;
415
416 future = dex_scheduler_spawn (scheduler, stack_size,
417 dex_scheduler_spawn_trampoline_fiber,
418 g_steal_pointer (&state),
419 (GDestroyNotify) dex_scheduler_spawn_trampoline_free);
420 }
421
422 g_clear_pointer (&values, g_array_unref);
423 g_free (errmsg);
424
425 return future;
426 }