Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : #include <stdbool.h>
28 :
29 : #include "common.h"
30 :
31 : // Everything from here to the matching pop is the public ABI and the shared
32 : // library exports it. The library builds with -fvisibility=hidden, so anything
33 : // outside these blocks stays internal.
34 : #pragma GCC visibility push(default)
35 :
36 : // A generic thread pool. With queue_capacity 0 the task queue is unbounded and
37 : // a submit never waits for room; with a capacity N a submit waits while N tasks
38 : // are queued (cthrpool_try_submit refuses instead). cthrpool_shutdown_drain
39 : // finishes the queue before the workers stop, cthrpool_shutdown_immediate
40 : // discards it.
41 : //
42 : // Every public function may run at the same time as any other on the same live
43 : // handle, shutdowns and destroy included. Both shutdowns are idempotent: A
44 : // second call does no work of its own but blocks until no worker is alive. An
45 : // immediate shutdown that arrives during a drain escalates it and discards what
46 : // is left in the queue.
47 : //
48 : // The pool never allocates, copies or frees the void * result of a future.
49 : // Whoever calls cthrpool_future_get owns it and frees it the way the task
50 : // allocated it; cthrpool_future_free frees only the future itself.
51 : typedef struct cthread_pool cthread_pool;
52 :
53 : // The handle is an opaque value (slot index plus generation), never a pointer.
54 : // Don't cast it to or from void *. Compare it with CTHRPOOL_NULL, which is 0,
55 : // so `if (!pool)` works. Every use goes through the library's slot table, so a
56 : // stale handle is always detected and never dereferenced.
57 : typedef uint64_t cthrpool;
58 :
59 : // "No pool": The failure value of a create and the value a destroy leaves in
60 : // the handle, so a handle can be tested for validity.
61 : #define CTHRPOOL_NULL ((cthrpool)0)
62 :
63 : // A future holds the void * result of a task that may not have run yet.
64 : typedef struct cthrpool_future cthrpool_future;
65 :
66 : // Creates a pool of num_threads (at least 1) worker threads that allocates
67 : // through mprocs, your allocator table, or NULL for malloc and free (a future
68 : // always uses malloc and free). queue_capacity 0 means an unbounded task
69 : // queue, N a bounded one whose submits wait or refuse while N tasks are queued;
70 : // ccol_invalid_size is refused. Gives the handle, or CTHRPOOL_NULL with an
71 : // error string in *err_str when err_str isn't NULL. Destroy it with
72 : // cthrpool_destroy().
73 : //
74 : // The pool keeps idle task nodes for reuse (up to max(num_threads * 4, 32768)),
75 : // so mprocs doesn't see an allocation and a free per submission. Workers mark
76 : // themselves on one thread-specific key that the library creates for the whole
77 : // process; when no key is left (PTHREAD_KEYS_MAX) every create fails. The key
78 : // is deleted when the library unloads with no pool left.
79 : cthrpool cthrpool_create_mp(size_t num_threads, size_t queue_capacity,
80 : ccol_memmgmt_procs *mprocs, char **err_str);
81 :
82 : // Creates a pool of num_threads (at least 1) worker threads that allocates
83 : // with malloc and free. queue_capacity 0 means an unbounded task queue, N a
84 : // bounded one whose submits wait or refuse while N tasks are queued;
85 : // ccol_invalid_size is refused. Gives the handle, or CTHRPOOL_NULL with an
86 : // error string in *err_str when err_str isn't NULL. Destroy it with
87 : // cthrpool_destroy().
88 : static inline __attribute__((always_inline)) cthrpool
89 : cthrpool_create(size_t num_threads, size_t queue_capacity, char **err_str) {
90 683 : return cthrpool_create_mp(num_threads, queue_capacity, NULL, err_str);
91 : }
92 :
93 : // Internal: Destroys a pool. It's the body of cthrpool_destroy(); use the
94 : // macro, which also clears the handle.
95 : //
96 : // CTHRPOOL_NULL is a no-op. Any other handle that isn't live (already
97 : // destroyed, being destroyed by another thread, or garbage) is a fatal error,
98 : // and so is a destroy from a task or on_complete callback running on this
99 : // pool's own worker. When no shutdown ran, a drain shutdown runs first; then it
100 : // waits for every call that resolved the handle on another thread to leave
101 : // before it frees anything.
102 : void cthrpool__destroy(cthrpool pool);
103 :
104 : // Internal: Destroys *pp and clears it. The _scoped macros attach it with
105 : // ccol__destructor so a pool goes away with its scope.
106 : static inline __attribute__((always_inline)) void cthrpool__destroy_cleanup(
107 : cthrpool *pp) {
108 2 : if (pp && *pp) {
109 2 : cthrpool__destroy(*pp);
110 2 : *pp = CTHRPOOL_NULL;
111 : }
112 2 : }
113 :
114 : // Destroys the pool and sets the handle to CTHRPOOL_NULL, so the variable can't
115 : // be used again by mistake. This is how a pool is destroyed. pool must be a
116 : // modifiable lvalue and is evaluated once; CTHRPOOL_NULL does nothing. When no
117 : // shutdown ran, it first runs every queued task and joins the workers, as
118 : // cthrpool_shutdown_drain() does. Then it waits for every call that other
119 : // threads are making on the handle to return before it frees anything. A stale
120 : // handle, or a destroy from one of the pool's own tasks or on_complete
121 : // callbacks, is a fatal error.
122 : #define cthrpool_destroy(pool) \
123 : ccol__cthrpool_destroy_impl( \
124 : pool, ccol__uniq(ccol__cthrpool_destroy_slot, __COUNTER__))
125 :
126 : // Internal: The body of cthrpool_destroy(), destroying *&(pool) and clearing
127 : // it. slot comes from ccol__uniq(), so destroy macros can nest without -Wshadow
128 : // warnings.
129 : #define ccol__cthrpool_destroy_impl(pool, slot) \
130 : do { \
131 : __typeof__(pool) *slot = &(pool); \
132 : cthrpool__destroy(*slot); \
133 : *slot = CTHRPOOL_NULL; \
134 : } while (0)
135 :
136 : // Declares an uninitialized pool handle variable called name, for code that
137 : // creates the pool later with cthrpool_create() or cthrpool_create_mp() and
138 : // destroys it with cthrpool_destroy().
139 : #define cthrpool_declare(name) cthrpool name
140 :
141 : // Declares a pool handle variable called name, set to CTHRPOOL_NULL, whose
142 : // pool is destroyed when the variable goes out of scope, so no exit path can
143 : // leak it. Create the pool into it later with cthrpool_create() or
144 : // cthrpool_create_mp().
145 : #define cthrpool_declare_scoped(name) \
146 : cthrpool name ccol__destructor(cthrpool__destroy_cleanup) = CTHRPOOL_NULL
147 :
148 : // Declares a pool handle variable called name and creates a pool of
149 : // num_threads (at least 1) workers in one step, with the default allocator, for
150 : // code that treats a failed create as fatal: A failed create stops the program
151 : // with a fatal error that names the variable and the reason. queue_capacity 0
152 : // means an unbounded task queue, N a bounded one. Destroy the pool with
153 : // cthrpool_destroy().
154 : //
155 : // cthrpool_construct(pool, 4, 256);
156 : // cthrpool_submit(pool, my_fn, my_arg, NULL);
157 : // cthrpool_shutdown_drain(pool);
158 : // cthrpool_destroy(pool);
159 : #define cthrpool_construct(name, num_threads, queue_capacity) \
160 : cthrpool name = CTHRPOOL_NULL; \
161 : do { \
162 : char *cthrpool__err = NULL; \
163 : (name) = cthrpool_create((num_threads), (queue_capacity), &cthrpool__err); \
164 : if (!(name)) { \
165 : ccol__fatal_err("cthrpool_construct('%s'): %s", #name, \
166 : cthrpool__err ? cthrpool__err : "unknown error"); \
167 : } \
168 : } while (0)
169 :
170 : // Declares a pool handle variable called name and creates a pool of
171 : // num_threads (at least 1) workers in one step, with the default allocator; a
172 : // failed create stops the program with a fatal error that names the variable
173 : // and the reason. queue_capacity 0 means an unbounded task queue, N a bounded
174 : // one. The pool is destroyed when name goes out of scope, so no exit path can
175 : // leak it.
176 : #define cthrpool_construct_scoped(name, num_threads, queue_capacity) \
177 : cthrpool name ccol__destructor(cthrpool__destroy_cleanup) = CTHRPOOL_NULL; \
178 : do { \
179 : char *cthrpool__err = NULL; \
180 : (name) = cthrpool_create((num_threads), (queue_capacity), &cthrpool__err); \
181 : if (!(name)) { \
182 : ccol__fatal_err("cthrpool_construct_scoped('%s'): %s", #name, \
183 : cthrpool__err ? cthrpool__err : "unknown error"); \
184 : } \
185 : } while (0)
186 :
187 : // Queues fn(arg) to run on a worker. It's the ordinary way to hand work to the
188 : // pool, and it waits for room on a full bounded queue, which gives a producer
189 : // backpressure. The exception is a caller that is a task or on_complete
190 : // callback of this same pool: Only the workers can free a slot, so it gives
191 : // ccol_container_full at once. It gives ccol_success, ccol_invalid_args (bad
192 : // handle or NULL fn), ccol_not_permitted (shutdown started),
193 : // ccol_not_enough_memory or that ccol_container_full.
194 : //
195 : // on_complete (may be NULL) runs exactly once for every accepted task: On the
196 : // worker with ran == true right after fn, or with ran == false when a shutdown
197 : // or the destroy of a pool inherited across fork() discards the task, so it can
198 : // always release arg. The ran == false calls run on the thread that discards,
199 : // before it returns, with no pool lock held. Such a call counts as a callback
200 : // of the pool: A wait or shutdown of the same pool from it is a no-op, a
201 : // destroy is fatal and a submit gives ccol_not_permitted (ccol_invalid_args
202 : // inside the destroy of an inherited pool). A failed submit accepts nothing and
203 : // never calls on_complete.
204 : ccol_retval cthrpool_submit(cthrpool pool, void (*fn)(void *), void *arg,
205 : void (*on_complete)(void *arg, bool ran));
206 :
207 : // Queues fn(arg) to run on a worker without ever waiting, for a producer that
208 : // must not block. on_complete (may be NULL) runs exactly once for every
209 : // accepted task: With ran == true after fn on the worker, or with ran == false
210 : // when a shutdown discards the task, so it can always release arg. It gives
211 : // ccol_success, ccol_container_full when a bounded queue is full,
212 : // ccol_invalid_args (bad handle or NULL fn), ccol_not_permitted (shutdown
213 : // started) or ccol_not_enough_memory. A failed submit accepts nothing and never
214 : // calls on_complete.
215 : ccol_retval cthrpool_try_submit(cthrpool pool, void (*fn)(void *), void *arg,
216 : void (*on_complete)(void *arg, bool ran));
217 :
218 : // Queues fn(arg) to run on a worker, waiting at most timeout_us microseconds
219 : // for room in a full bounded queue, for a producer that can wait a little but
220 : // not for ever. The deadline is on CLOCK_MONOTONIC, so wall clock changes don't
221 : // affect it. 0 doesn't wait, and a huge value such as UINT64_MAX saturates and
222 : // waits as long as the queue stays full. A call from a task or on_complete
223 : // callback of this pool never waits. on_complete (may be NULL) runs exactly
224 : // once for every accepted task: With ran == true after fn, or ran == false when
225 : // a shutdown discards it. It gives ccol_success, ccol_timed_out,
226 : // ccol_container_full (full queue with timeout 0, or a call from this pool's
227 : // own task), ccol_invalid_args (bad handle or NULL fn), ccol_not_permitted
228 : // (shutdown started), ccol_not_enough_memory, or ccol_unexpected_failure when
229 : // the wait itself fails. A failed submit never calls on_complete.
230 : ccol_retval cthrpool_timed_submit(cthrpool pool, void (*fn)(void *), void *arg,
231 : void (*on_complete)(void *arg, bool ran),
232 : uint64_t timeout_us);
233 :
234 : // Queues fn(arg) and gives a future for its void * result, so the submitting
235 : // thread can collect what the task computed with cthrpool_future_get(). It
236 : // waits with no time limit for room in a full bounded queue, except when the
237 : // caller is a task or on_complete callback of this same pool. Gives NULL on
238 : // failure. When rv_out isn't NULL it gets a code on every return: ccol_success,
239 : // ccol_invalid_args (bad handle or NULL fn), ccol_not_permitted (shutdown
240 : // started), ccol_container_full (a full bounded queue and a caller from this
241 : // pool's own task), or ccol_not_enough_memory. Call cthrpool_future_free()
242 : // exactly once for every future you get.
243 : cthrpool_future *cthrpool_submit_future(cthrpool pool, void *(*fn)(void *),
244 : void *arg, ccol_retval *rv_out);
245 :
246 : // Queues fn(arg) without ever waiting and puts a future for its void * result
247 : // in *out, for a caller that must not block; *out is set to NULL on failure,
248 : // and out must not be NULL. It gives ccol_success, ccol_container_full when a
249 : // bounded queue is full, ccol_invalid_args (bad handle, NULL fn or NULL out),
250 : // ccol_not_permitted (shutdown started) or ccol_not_enough_memory. Collect the
251 : // result with cthrpool_future_get(), and call cthrpool_future_free() exactly
252 : // once for every future you get.
253 : ccol_retval cthrpool_try_submit_future(cthrpool pool, void *(*fn)(void *),
254 : void *arg, cthrpool_future **out);
255 :
256 : // Queues fn(arg), waiting at most timeout_us microseconds on CLOCK_MONOTONIC
257 : // for room in a full bounded queue, and puts a future for its void * result in
258 : // *out; *out is set to NULL on failure, and out must not be NULL. 0 doesn't
259 : // wait, and a huge value such as UINT64_MAX waits as long as the queue stays
260 : // full. A call from a task or on_complete callback of this pool never waits.
261 : // It gives ccol_success, ccol_timed_out, ccol_container_full (full queue with
262 : // timeout 0, or a call from this pool's own task), ccol_invalid_args (bad
263 : // handle, NULL fn or NULL out), ccol_not_permitted (shutdown started),
264 : // ccol_not_enough_memory, or ccol_unexpected_failure when the wait itself
265 : // fails. Call cthrpool_future_free() exactly once for every future you get.
266 : ccol_retval cthrpool_timed_submit_future(cthrpool pool, void *(*fn)(void *),
267 : void *arg, uint64_t timeout_us,
268 : cthrpool_future **out);
269 :
270 : // Blocks until the future has a result and gives it, so the caller can collect
271 : // what the task computed; NULL when an immediate shutdown cancelled the task,
272 : // and at once for a NULL f. It doesn't free the future. Any number of threads
273 : // may wait on one future; each holds its own reference during the call, so the
274 : // future outlives all of them. From here on the caller owns the result.
275 : void *cthrpool_future_get(cthrpool_future *f);
276 :
277 : // Tells, without blocking, whether the future has a result or was cancelled,
278 : // so a caller can poll instead of waiting in cthrpool_future_get(). Gives
279 : // false for a NULL f.
280 : bool cthrpool_future_done(cthrpool_future *f);
281 :
282 : // Tells whether an immediate shutdown cancelled the future, which is how a
283 : // caller tells a cancelled task from one that returned NULL. Gives false for a
284 : // NULL f.
285 : bool cthrpool_future_cancelled(cthrpool_future *f);
286 :
287 : // Gives up the caller's reference, which is how a future is released. Call it
288 : // exactly once per successful future submit, whether or not you called
289 : // cthrpool_future_get(); without a get the result is thrown away and not
290 : // freed. Threads already inside cthrpool_future_get() keep the future alive.
291 : // NULL does nothing. Don't use f after this call.
292 : void cthrpool_future_free(cthrpool_future *f);
293 :
294 : // Creates a future with no pool behind it, so a producer that isn't a cthrpool
295 : // worker (an event-driven engine, for example) can hand a result to a waiting
296 : // thread. The producer calls cthrpool_future_fulfill() exactly once and the
297 : // consumer calls cthrpool_future_free() exactly once, in any order. Like every
298 : // future it's allocated with plain malloc, so producer and consumer don't need
299 : // to share an allocator. Gives NULL, with *err_str set, when it fails.
300 : cthrpool_future *cthrpool_future_create_detached(char **err_str);
301 :
302 : // Delivers result to a detached future, wakes every waiter and drops the
303 : // producer's reference (freeing the future when it was the last one). It's the
304 : // producer's half of cthrpool_future_create_detached(); never call it on a
305 : // future from a submit. It gives ccol_success, ccol_invalid_args for a NULL f,
306 : // or ccol_not_permitted when f is already fulfilled.
307 : ccol_retval cthrpool_future_fulfill(cthrpool_future *f, void *result);
308 :
309 : // Blocks until the queue is empty and no task runs, so a caller can wait for a
310 : // batch of work without shutting the pool down; the pool stays usable. Nobody
311 : // may submit while it waits. It doesn't wait for the ran == false callbacks of
312 : // an immediate shutdown running on another thread. It's a no-op for a bad
313 : // handle and for a call from one of this pool's own tasks or callbacks (which
314 : // would wait for itself).
315 : void cthrpool_wait(cthrpool pool);
316 :
317 : // Runs every queued task, then stops and joins the workers: The graceful way to
318 : // end a pool. After it the pool refuses new tasks. Calling it before destroy is
319 : // optional. It's a no-op for a bad handle, and a no-op that doesn't block for a
320 : // call from one of this pool's own tasks or callbacks (a worker can't join
321 : // itself).
322 : void cthrpool_shutdown_drain(cthrpool pool);
323 :
324 : // Stops the pool without running its queue, for a caller that must stop fast.
325 : // Every queued task is discarded (its future becomes cancelled and its
326 : // on_complete runs with ran == false on this thread before it returns), each
327 : // worker finishes its current task, and all of them are joined. During a drain
328 : // it escalates the drain. No-op for a bad handle or a call from one of this
329 : // pool's own tasks or callbacks.
330 : void cthrpool_shutdown_immediate(cthrpool pool);
331 :
332 : // Gives the number of queued tasks that no worker has taken yet, for
333 : // monitoring and backpressure decisions; 0 for a bad handle.
334 : size_t cthrpool_pending_count(cthrpool pool);
335 :
336 : // Gives the number of tasks the workers are running right now, for
337 : // monitoring; 0 for a bad handle.
338 : size_t cthrpool_active_count(cthrpool pool);
339 :
340 : #pragma GCC visibility pop
|