Debian Codegraph @

src/dex-thread-pool.c

raw symbols SCIP
1 /* dex-thread-pool.c
2 *
3 * Copyright 2026 Christian Hergert <[email protected]>
4 *
5 * This library is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2.1 of the
8 * License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: LGPL-2.1-or-later
19 */
20
21 #include "config.h"
22
23 #include "dex-error.h"
24 #include "dex-object-private.h"
25 #include "dex-promise.h"
26 #include "dex-thread-pool.h"
27 #include "dex-waiter-private.h"
28
29 /**
30 * DexThreadPool:
31 *
32 * `DexThreadPool` is a thread pool for managing native OS threads similar
33 * to [[email protected]].
34 *
35 * The threads managed by `DexThreadPool` do not contain a
36 * [[email protected]] which means that you cannot await
37 * futures or schedule [[email protected]] from a worker thread.
38 *
39 * Threads are created up-front from [[email protected]].
40 *
41 * `DexThreadPool` primarily exists for situations where you are
42 * using blocking external libraries and want to avoid calling
43 * [[email protected]_spawn] without any sort of queuing or bounding
44 * on the permitted concurrency.
45 *
46 * Since: 1.2
47 */
48
49 typedef enum
50 {
51 DEX_THREAD_POOL_STATE_RUNNING,
52 DEX_THREAD_POOL_STATE_DRAINING,
53 DEX_THREAD_POOL_STATE_CANCEL_QUEUED,
54 DEX_THREAD_POOL_STATE_CLOSED,
55 } DexThreadPoolState;
56
57 typedef struct
58 {
59 char *thread_name;
60 DexThreadFunc thread_func;
61 gpointer user_data;
62 GDestroyNotify user_data_destroy;
63 DexPromise *promise;
64 guint close_request : 1;
65 } DexThreadPoolItem;
66
67 struct _DexThreadPool
68 {
69 DexObject parent_instance;
70 guint n_threads;
71 GThread **threads;
72 GAsyncQueue *queue;
73 DexPromise *close_promise;
74 GMutex mutex;
75 DexThreadPoolState state;
76 guint joined : 1;
77 };
78
79 typedef struct _DexThreadPoolClass
80 {
81 DexObjectClass parent_class;
82 } DexThreadPoolClass;
83
84 DEX_DEFINE_FINAL_TYPE (DexThreadPool, dex_thread_pool, DEX_TYPE_OBJECT)
85
86 #undef DEX_TYPE_THREAD_POOL
87 #define DEX_TYPE_THREAD_POOL dex_thread_pool_type
88
89 static void
90 dex_thread_pool_item_free (DexThreadPoolItem *item)
91 {
92 if (item == NULL)
93 return;
94
95 if (item->user_data_destroy != NULL)
96 item->user_data_destroy (item->user_data);
97
98 dex_clear (&item->promise);
99 g_clear_pointer (&item->thread_name, g_free);
100 g_free (item);
101 }
102
103 static gpointer
104 dex_thread_pool_worker (gpointer data)
105 {
106 GAsyncQueue *queue = data;
107
108 for (;;)
109 {
110 DexThreadPoolItem *item;
111 DexFuture *future;
112
113 item = g_async_queue_pop (queue);
114 if (item == NULL)
115 break;
116
117 if (item->close_request)
118 {
119 dex_thread_pool_item_free (item);
120 break;
121 }
122
123 future = item->thread_func (item->user_data);
124
125 if (future != NULL)
126 {
127 DexWaiter *waiter = dex_waiter_new (future);
128 GError *error = NULL;
129 const GValue *value;
130
131 dex_waiter_wait (waiter);
132 value = dex_future_get_value (DEX_FUTURE (waiter), &error);
133
134 if (value != NULL)
135 dex_promise_resolve (item->promise, value);
136 else
137 dex_promise_reject (item->promise, g_steal_pointer (&error));
138
139 dex_unref (waiter);
140 dex_unref (future);
141 }
142 else
143 {
144 dex_promise_resolve_boolean (item->promise, TRUE);
145 }
146
147 dex_thread_pool_item_free (item);
148 }
149
150 g_async_queue_unref (queue);
151
152 return NULL;
153 }
154
155 static void
156 dex_thread_pool_finalize (DexObject *object)
157 {
158 DexThreadPool *self = (DexThreadPool *)object;
159 guint n_threads = self->threads != NULL ? self->n_threads : 0;
160
161 g_mutex_lock (&self->mutex);
162 if (self->state == DEX_THREAD_POOL_STATE_RUNNING)
163 self->state = DEX_THREAD_POOL_STATE_DRAINING;
164 g_mutex_unlock (&self->mutex);
165
166 if (!self->joined && self->threads != NULL)
167 {
168 DexThreadPoolItem *item;
169
170 for (guint i = 0; i < n_threads; i++)
171 {
172 if (self->threads[i] == NULL)
173 continue;
174
175 item = g_new0 (DexThreadPoolItem, 1);
176 item->close_request = TRUE;
177 g_async_queue_push (self->queue, item);
178 }
179
180 for (guint i = 0; i < n_threads; i++)
181 {
182 GThread *thread = self->threads[i];
183
184 if (thread == NULL)
185 continue;
186
187 g_thread_join (thread);
188 g_thread_unref (thread);
189 }
190 }
191
192 g_clear_pointer (&self->close_promise, dex_unref);
193 g_clear_pointer (&self->queue, g_async_queue_unref);
194 g_clear_pointer (&self->threads, g_free);
195 g_mutex_clear (&self->mutex);
196
197 DEX_OBJECT_CLASS (dex_thread_pool_parent_class)->finalize (object);
198 }
199
200 static void
201 dex_thread_pool_class_init (DexThreadPoolClass *klass)
202 {
203 DexObjectClass *object_class = DEX_OBJECT_CLASS (klass);
204
205 object_class->finalize = dex_thread_pool_finalize;
206 }
207
208 static void
209 dex_thread_pool_init (DexThreadPool *self)
210 {
211 g_mutex_init (&self->mutex);
212 self->queue = g_async_queue_new ();
213 }
214
215 /**
216 * dex_thread_pool_new:
217 * @n_threads: the number of threads to create
218 *
219 * Creates a fixed-size pool of reusable operating system threads.
220 *
221 * Returns: (transfer full): a new `DexThreadPool`
222 *
223 * Since: 1.2
224 */
225 DexThreadPool *
226 dex_thread_pool_new (guint n_threads)
227 {
228 DexThreadPool *self;
229 guint n_started = 0;
230
231 g_return_val_if_fail (n_threads > 0, NULL);
232
233 self = (DexThreadPool *)dex_object_create_instance (dex_thread_pool_type);
234 self->threads = g_new0 (GThread *, n_threads);
235 self->n_threads = n_threads;
236 self->state = DEX_THREAD_POOL_STATE_RUNNING;
237
238 for (guint i = 0; i < n_threads; i++)
239 {
240 self->threads[i] = g_thread_try_new ("dex-thread-pool",
241 dex_thread_pool_worker,
242 g_async_queue_ref (self->queue),
243 NULL);
244
245 if (self->threads[i] == NULL)
246 {
247 self->n_threads = n_started;
248 dex_unref (self);
249 return NULL;
250 }
251
252 n_started++;
253 }
254
255 return self;
256 }
257
258 /**
259 * dex_thread_pool_get_n_threads:
260 * @pool: a `DexThreadPool`
261 *
262 * Gets the fixed number of threads owned by the pool.
263 *
264 * Returns: the number of threads in the pool
265 *
266 * Since: 1.2
267 */
268 guint
269 dex_thread_pool_get_n_threads (DexThreadPool *pool)
270 {
271 g_return_val_if_fail (DEX_IS_THREAD_POOL (pool), 0);
272
273 return pool->n_threads;
274 }
275
276 /**
277 * dex_thread_pool_submit:
278 * @pool: a `DexThreadPool`
279 * @thread_name: (nullable): the name to use for debugging the returned future
280 * @thread_func: the function to run on a pooled thread
281 * @user_data: closure data for @thread_func
282 * @user_data_destroy: destroy notify for @user_data
283 *
284 * Queues blocking work to run on one of the pool's reusable threads.
285 *
286 * The provided @thread_name is applied to the returned future using
287 * `dex_future_set_static_name()` so that tracing and debugging tools can
288 * identify the work item. It does not rename the underlying OS worker thread.
289 *
290 * Returns: (transfer full): a future that resolves when the work completes
291 *
292 * Since: 1.2
293 */
294 DexFuture *
295 dex_thread_pool_submit (DexThreadPool *pool,
296 const char *thread_name,
297 DexThreadFunc thread_func,
298 gpointer user_data,
299 GDestroyNotify user_data_destroy)
300 {
301 DexThreadPoolItem *item;
302 DexPromise *promise;
303
304 dex_return_error_if_fail (DEX_IS_THREAD_POOL (pool));
305 dex_return_error_if_fail (thread_func != NULL);
306
307 if (thread_name != NULL)
308 thread_name = g_intern_string (thread_name);
309 else
310 thread_name = "[dex-thread-pool]";
311
312 promise = dex_promise_new ();
313 dex_future_set_static_name (DEX_FUTURE (promise), thread_name);
314
315 item = g_new0 (DexThreadPoolItem, 1);
316 item->thread_name = g_strdup (thread_name);
317 item->thread_func = thread_func;
318 item->user_data = user_data;
319 item->user_data_destroy = user_data_destroy;
320 item->promise = dex_ref (promise);
321
322 g_mutex_lock (&pool->mutex);
323 if (pool->state != DEX_THREAD_POOL_STATE_RUNNING)
324 {
325 g_mutex_unlock (&pool->mutex);
326 dex_promise_reject (promise,
327 g_error_new_literal (DEX_ERROR,
328 DEX_ERROR_SEMAPHORE_CLOSED,
329 "Thread pool is closed"));
330 dex_thread_pool_item_free (item);
331 return DEX_FUTURE (promise);
332 }
333
334 g_async_queue_push (pool->queue, item);
335 g_mutex_unlock (&pool->mutex);
336
337 return DEX_FUTURE (promise);
338 }
339
340 static void
341 dex_thread_pool_cancel_queued (DexThreadPool *pool,
342 GPtrArray *queued_items)
343 {
344 DexThreadPoolItem *item;
345
346 while ((item = g_async_queue_try_pop (pool->queue)) != NULL)
347 {
348 g_ptr_array_add (queued_items, item);
349 }
350 }
351
352 static void
353 dex_thread_pool_push_close_requests (DexThreadPool *pool)
354 {
355 for (guint i = 0; i < pool->n_threads; i++)
356 {
357 DexThreadPoolItem *item = g_new0 (DexThreadPoolItem, 1);
358
359 item->close_request = TRUE;
360 g_async_queue_push (pool->queue, item);
361 }
362 }
363
364 typedef struct
365 {
366 DexThreadPool *pool;
367 DexPromise *promise;
368 } DexThreadPoolCloseState;
369
370 static gpointer
371 dex_thread_pool_close_thread (gpointer data)
372 {
373 DexThreadPoolCloseState *state = data;
374
375 dex_thread_pool_push_close_requests (state->pool);
376
377 for (guint i = 0; i < state->pool->n_threads; i++)
378 {
379 GThread *thread = state->pool->threads[i];
380
381 g_thread_join (thread);
382 g_thread_unref (thread);
383 }
384
385 g_mutex_lock (&state->pool->mutex);
386 state->pool->joined = TRUE;
387 g_mutex_unlock (&state->pool->mutex);
388
389 dex_promise_resolve_boolean (state->promise, TRUE);
390 dex_clear (&state->pool->close_promise);
391 dex_clear (&state->pool);
392 dex_clear (&state->promise);
393 g_free (state);
394
395 return NULL;
396 }
397
398 /**
399 * dex_thread_pool_close:
400 * @pool: a `DexThreadPool`
401 * @mode: shutdown policy for queued work
402 *
403 * Begins shutting down the pool and prevents new submissions.
404 *
405 * Returns: (transfer full): a future that resolves when shutdown completes
406 */
407 DexFuture *
408 dex_thread_pool_close (DexThreadPool *pool,
409 DexThreadPoolShutdownMode mode)
410 {
411 gboolean spawn_close_thread = FALSE;
412 gboolean cancel_queued = FALSE;
413 DexPromise *close_promise = NULL;
414 GPtrArray *queued_items = NULL;
415
416 dex_return_error_if_fail (DEX_IS_THREAD_POOL (pool));
417
418 g_mutex_lock (&pool->mutex);
419 if (pool->state == DEX_THREAD_POOL_STATE_RUNNING)
420 {
421 cancel_queued = (mode == DEX_THREAD_POOL_SHUTDOWN_CANCEL_QUEUED);
422 pool->state = cancel_queued ?
423 DEX_THREAD_POOL_STATE_CANCEL_QUEUED :
424 DEX_THREAD_POOL_STATE_DRAINING;
425 pool->close_promise = dex_promise_new ();
426 spawn_close_thread = TRUE;
427
428 if (cancel_queued)
429 {
430 queued_items = g_ptr_array_new ();
431 dex_thread_pool_cancel_queued (pool, queued_items);
432 }
433 }
434
435 if (pool->close_promise != NULL)
436 close_promise = dex_ref (pool->close_promise);
437 g_mutex_unlock (&pool->mutex);
438
439 if (queued_items != NULL)
440 {
441 for (guint i = 0; i < queued_items->len; i++)
442 {
443 DexThreadPoolItem *item = g_ptr_array_index (queued_items, i);
444
445 if (item->promise != NULL)
446 dex_promise_reject (item->promise,
447 g_error_new_literal (DEX_ERROR,
448 DEX_ERROR_SEMAPHORE_CLOSED,
449 "Thread pool is closed"));
450 dex_thread_pool_item_free (item);
451 }
452
453 g_ptr_array_free (queued_items, TRUE);
454 }
455
456 if (close_promise == NULL)
457 {
458 DexPromise *promise = dex_promise_new ();
459
460 dex_promise_resolve_boolean (promise, TRUE);
461 return DEX_FUTURE (promise);
462 }
463
464 if (spawn_close_thread)
465 {
466 DexThreadPoolCloseState *state = g_new0 (DexThreadPoolCloseState, 1);
467
468 state->pool = dex_ref (pool);
469 state->promise = dex_ref (close_promise);
470 g_thread_unref (g_thread_new ("dex-thread-pool-close",
471 dex_thread_pool_close_thread,
472 state));
473 }
474
475 return DEX_FUTURE (close_promise);
476 }