ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
thread_pool.h File Reference

🧵 Generic thread pool abstraction for managing worker threads More...

Go to the source code of this file.

Data Structures

struct  thread_pool_work_entry
 One queued function call waiting for a thread-pool worker. More...
struct  thread_pool_entry
 Thread handle and shutdown metadata for one pool-owned thread. More...
struct  thread_pool
 Thread pool structure. More...

Macros

#define THREAD_POOL_NAME_BUFFER_SIZE   64

Typedefs

typedef struct thread_pool_entry thread_pool_entry_t
typedef struct thread_pool_work_entry thread_pool_work_entry_t
 One queued function call waiting for a thread-pool worker.

Functions

thread_pool_t * thread_pool_create (const char *pool_name)
 Create a new thread pool (long-lived threads mode).
thread_pool_t * thread_pool_create_with_workers (const char *pool_name, size_t num_workers)
 Create a new thread pool in work queue mode.
void thread_pool_destroy (thread_pool_t *pool)
 Destroy a thread pool.
asciichat_error_t thread_pool_queue_work (const char *name, thread_pool_t *pool, void *(*work_func)(void *), void *work_arg)
 Queue a named work item to a work queue pool.
asciichat_error_t thread_pool_spawn (thread_pool_t *pool, void *(*thread_func)(void *), void *thread_arg, int stop_id, const char *thread_name)
 Spawn a worker thread in the pool.
asciichat_error_t thread_pool_stop_all (thread_pool_t *pool)
 Stop all threads in the pool in stop_id order.
size_t thread_pool_get_count (const thread_pool_t *pool)
 Get thread count in the pool.
bool thread_pool_has_threads (const thread_pool_t *pool)
 Check if pool has any threads.
asciichat_error_t thread_pool_interrupt_all (thread_pool_t *pool, int sig)
 Send a signal to all threads in the pool.

Detailed Description

🧵 Generic thread pool abstraction for managing worker threads

Provides a reusable thread pool implementation for managing multiple worker threads with ordered cleanup support. This abstraction is used by:

  • tcp_server: Per-client thread pools for receive/send/render workers
  • Server: Background threads (stats logger, etc.)
  • ACDS: Background threads (rate limit cleanup, etc.)
  • Client: Capture and display threads

Features

  • Thread lifecycle management: Create, spawn, stop, and join threads
  • Ordered cleanup: Threads with lower stop_id values are stopped first
  • Thread naming: Assign names to threads for debugging
  • Thread-safe: All operations are protected with mutexes
  • Flexible: Supports both entity-bound pools and global singleton pools

Usage Pattern

// Create thread pool
thread_pool_t *pool = thread_pool_create("my_pool");
// Spawn workers with ordered cleanup
thread_pool_spawn(pool, worker_func1, arg1, 1, "worker1"); // Stop first
thread_pool_spawn(pool, worker_func2, arg2, 2, "worker2"); // Stop second
thread_pool_spawn(pool, worker_func3, arg3, 3, "worker3"); // Stop last
// Stop all threads in stop_id order (1 → 2 → 3)
// Destroy pool (frees all resources)
struct thread_pool thread_pool_t
One queued function call waiting for a thread-pool worker.
void thread_pool_destroy(thread_pool_t *pool)
Destroy a thread pool.
thread_pool_t * thread_pool_create(const char *pool_name)
Create a new thread pool (long-lived threads mode).
Definition thread_pool.c:96
asciichat_error_t thread_pool_spawn(thread_pool_t *pool, void *(*thread_func)(void *), void *thread_arg, int stop_id, const char *thread_name)
Spawn a worker thread in the pool.
asciichat_error_t thread_pool_stop_all(thread_pool_t *pool)
Stop all threads in the pool in stop_id order.

Ordered Cleanup Example (Server Per-Client Threads)

// Client connection established
thread_pool_spawn(pool, receive_thread, client, 1, "receive_1");
thread_pool_spawn(pool, video_render, client, 2, "video_2");
thread_pool_spawn(pool, audio_render, client, 2, "audio_2");
thread_pool_spawn(pool, send_thread, client, 3, "send_3");
// Client disconnect - threads stopped in order:
// 1. Receive thread (stop_id=1) - no new data arrives
// 2. Render threads (stop_id=2) - no new frames generated
// 3. Send thread (stop_id=3) - all queued data sent

Background Thread Example (Stats Logger)

// Server startup
thread_pool_t *server_pool = thread_pool_create("server");
thread_pool_spawn(server_pool, stats_logger, NULL, 0, "stats");
// Server shutdown
thread_pool_stop_all(server_pool);
thread_pool_destroy(server_pool);
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

Definition in file thread_pool.h.

Macro Definition Documentation

◆ THREAD_POOL_NAME_BUFFER_SIZE

#define THREAD_POOL_NAME_BUFFER_SIZE   64

Definition at line 74 of file thread_pool.h.

Typedef Documentation

◆ thread_pool_entry_t

Definition at line 97 of file thread_pool.h.

◆ thread_pool_work_entry_t

One queued function call waiting for a thread-pool worker.

The pool stores the callback, its opaque argument, and the link to the next queued task. Queue ownership transfers to the pool when a task is submitted; workers remove and free entries after invoking the callback.

Function Documentation

◆ thread_pool_create()

thread_pool_t * thread_pool_create ( const char * pool_name)

Create a new thread pool (long-lived threads mode).

Allocates and initializes a thread pool structure. The pool starts empty with no threads. Use thread_pool_spawn() to add threads to the pool.

This mode is used for long-lived worker threads that run for the lifetime of the application or connection (e.g., stats logger, cleanup thread).

Parameters
pool_nameName for the pool (max 63 chars, used for debugging)
Returns
Pointer to new thread pool, or NULL on allocation failure

Definition at line 96 of file thread_pool.c.

96 {
98 if (!pool) {
99 SET_ERRNO(ERROR_MEMORY, "Failed to allocate thread pool");
100 return NULL;
101 }
102
103 memset(pool, 0, sizeof(*pool));
104
105 // Copy pool name (truncate if necessary)
106 if (pool_name) {
107 SAFE_STRNCPY(pool->name, pool_name, sizeof(pool->name));
108 } else {
109 SAFE_STRNCPY(pool->name, "unnamed", sizeof(pool->name));
110 }
111
112 // Initialize linked list
113 pool->threads = NULL;
114 pool->thread_count = 0;
115 pool->is_work_queue_mode = false;
116 pool->num_workers = 0;
117
118 // Initialize mutex
119 if (mutex_init(&pool->threads_mutex, "thread_pool") != 0) {
120 SAFE_FREE(pool);
121 SET_ERRNO(ERROR_THREAD, "Failed to initialize thread pool mutex");
122 return NULL;
123 }
124
125 NAMED_REGISTER_THREAD_POOL(pool, pool->name, NULL);
126
127 // Register sync primitives for debugging
128 NAMED_REGISTER_MUTEX(&pool->threads_mutex, "threads_mutex",
129 (uintptr_t)(const void *)(pool));
130
131 log_debug("Thread pool '%s' created (long-lived thread mode)", pool->name);
132 return pool;
133}
#define SET_ERRNO(code,...)
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define NAMED_REGISTER_THREAD_POOL(pool, name, parent_ptr)
Register a thread pool with automatic format specifier.
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_THREAD
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
mutex_t threads_mutex
Mutex protecting thread list.
bool is_work_queue_mode
True if using work queue mode.
thread_pool_entry_t * threads
Linked list of threads (sorted by stop_id).
size_t thread_count
Number of threads in pool.
size_t num_workers
Number of pre-created worker threads.
char name[64]
Pool name for debugging.

References ERROR_MEMORY, ERROR_THREAD, thread_pool::is_work_queue_mode, log_debug, thread_pool::name, NAMED_REGISTER_MUTEX, NAMED_REGISTER_THREAD_POOL, thread_pool::num_workers, SAFE_FREE, SAFE_MALLOC, SAFE_STRNCPY, SET_ERRNO, thread_pool::thread_count, thread_pool::threads, and thread_pool::threads_mutex.

Referenced by acds_server_init(), client_connection_create(), network_server_create(), and server_main().

◆ thread_pool_create_with_workers()

thread_pool_t * thread_pool_create_with_workers ( const char * pool_name,
size_t num_workers )

Create a new thread pool in work queue mode.

Creates a thread pool with pre-allocated worker threads that pull tasks from a work queue. Use thread_pool_queue_work() to add work to the pool.

This mode is used for short-lived tasks that need to be executed without creating new threads from callback context (e.g., WebSocket handlers).

Worker threads are created immediately and wait for work to be queued. The pool will not accept spawn() calls - use queue_work() instead.

Parameters
pool_nameName for the pool (max 63 chars, used for debugging)
num_workersNumber of pre-allocated worker threads
Returns
Pointer to new thread pool, or NULL on allocation failure

Definition at line 135 of file thread_pool.c.

136 {
137 if (num_workers == 0) {
138 SET_ERRNO(ERROR_INVALID_PARAM, "num_workers must be > 0");
139 return NULL;
140 }
141
143 if (!pool) {
144 SET_ERRNO(ERROR_MEMORY, "Failed to allocate thread pool");
145 return NULL;
146 }
147
148 memset(pool, 0, sizeof(*pool));
149
150 // Copy pool name
151 if (pool_name) {
152 SAFE_STRNCPY(pool->name, pool_name, sizeof(pool->name));
153 } else {
154 SAFE_STRNCPY(pool->name, "unnamed", sizeof(pool->name));
155 }
156
157 // Mark as work queue mode
158 pool->is_work_queue_mode = true;
159 pool->num_workers = num_workers;
160 pool->work_queue = NULL;
161 pool->shutdown_requested = false;
162
163 // Initialize mutexes
164 if (mutex_init(&pool->threads_mutex, "worker_list") != 0) {
165 SAFE_FREE(pool);
166 SET_ERRNO(ERROR_THREAD, "Failed to initialize threads_mutex");
167 return NULL;
168 }
169
170 if (mutex_init(&pool->work_queue_mutex, "pending_tasks") != 0) {
171 mutex_destroy(&pool->threads_mutex);
172 SAFE_FREE(pool);
173 SET_ERRNO(ERROR_THREAD, "Failed to initialize work_queue_mutex");
174 return NULL;
175 }
176
177 // Initialize condition variable
178 if (cond_init(&pool->work_available, "task_available") != 0) {
179 mutex_destroy(&pool->work_queue_mutex);
180 mutex_destroy(&pool->threads_mutex);
181 SAFE_FREE(pool);
182 SET_ERRNO(ERROR_THREAD, "Failed to initialize work_available condition");
183 return NULL;
184 }
185
186 // Create worker threads
187 for (size_t i = 0; i < num_workers; i++) {
188 thread_pool_entry_t *entry =
190 if (!entry) {
191 log_error("Failed to allocate worker entry %zu", i);
193 SET_ERRNO(ERROR_MEMORY, "Failed to allocate worker entry");
194 return NULL;
195 }
196
197 memset(entry, 0, sizeof(*entry));
198 entry->stop_id = 0;
199 entry->thread_func = thread_pool_worker_thread;
200 entry->thread_arg = pool;
201 SAFE_SNPRINTF(entry->name, sizeof(entry->name), "%s_worker_%zu", pool->name,
202 i);
203
204 // Create worker thread
205 if (platform_thread_create(&entry->thread, entry->name,
206 thread_pool_worker_thread, pool) != 0) {
207 log_error("Failed to create worker thread %zu", i);
208 SAFE_FREE(entry);
210 SET_ERRNO(ERROR_THREAD, "Failed to create worker thread %zu", i);
211 return NULL;
212 }
213
214 // Add to thread list
215 mutex_lock(&pool->threads_mutex);
216 entry->next = pool->threads;
217 pool->threads = entry;
218 pool->thread_count++;
219 mutex_unlock(&pool->threads_mutex);
220
221 log_debug("[ThreadPool] Created worker thread %zu for pool '%s'", i,
222 pool->name);
223 }
224
225 NAMED_REGISTER_THREAD_POOL(pool, pool->name, NULL);
226
227 // Register sync primitives for debugging
228 NAMED_REGISTER_MUTEX(&pool->threads_mutex, "threads_mutex",
229 (uintptr_t)(const void *)(pool));
230 NAMED_REGISTER_MUTEX(&pool->work_queue_mutex, "work_queue_mutex",
231 (uintptr_t)(const void *)(pool));
232 NAMED_REGISTER_COND(&pool->work_available, "work_available",
233 (uintptr_t)(const void *)(pool));
234
235 log_info("[ThreadPool] Created work queue pool '%s' with %zu worker threads",
236 pool->name, num_workers);
237 return pool;
238}
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define NAMED_REGISTER_COND(cond, name, parent_ptr)
Register a condition variable with automatic format specifier.
@ ERROR_INVALID_PARAM
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
platform_thread_t thread
Thread handle.
void *(* thread_func)(void *)
Thread function.
void * thread_arg
Thread argument.
struct thread_pool_entry * next
Linked list next pointer.
int stop_id
Cleanup order (lower = stop first, -1 = unordered).
char name[64]
Thread name for debugging.
cond_t work_available
Condition variable for workers to wait on.
bool shutdown_requested
Signal workers to exit.
thread_pool_work_entry_t * work_queue
Queue of pending work.
mutex_t work_queue_mutex
Mutex protecting work queue.
struct thread_pool_entry thread_pool_entry_t
Definition thread_pool.h:97

References ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_THREAD, thread_pool::is_work_queue_mode, log_debug, log_error, log_info, thread_pool::name, thread_pool_entry::name, NAMED_REGISTER_COND, NAMED_REGISTER_MUTEX, NAMED_REGISTER_THREAD_POOL, thread_pool_entry::next, thread_pool::num_workers, SAFE_FREE, SAFE_MALLOC, SAFE_SNPRINTF, SAFE_STRNCPY, SET_ERRNO, thread_pool::shutdown_requested, thread_pool_entry::stop_id, thread_pool_entry::thread, thread_pool_entry::thread_arg, thread_pool::thread_count, thread_pool_entry::thread_func, thread_pool_destroy(), thread_pool::threads, thread_pool::threads_mutex, thread_pool::work_available, thread_pool::work_queue, and thread_pool::work_queue_mutex.

Referenced by websocket_server_init().

◆ thread_pool_destroy()

void thread_pool_destroy ( thread_pool_t * pool)

Destroy a thread pool.

Stops all threads (if not already stopped), waits for them to exit, and frees all pool resources. It's safe to call this even if threads are still running - they will be stopped first.

Parameters
poolThread pool to destroy (NULL is safe, does nothing)

Definition at line 240 of file thread_pool.c.

240 {
241 if (!pool) {
242 return;
243 }
244
245 log_debug(
246 "Destroying thread pool '%s' (thread_count=%zu, work_queue_mode=%d)",
247 pool->name, pool->thread_count, pool->is_work_queue_mode);
248
249 // Stop all threads first (if not already stopped)
250 if (pool->thread_count > 0) {
251 log_debug("Thread pool '%s' has %zu threads, stopping them first",
252 pool->name, pool->thread_count);
254 log_debug(
255 "After thread_pool_stop_all: pool->threads=%p, pool->thread_count=%zu",
256 (void *)pool->threads, pool->thread_count);
257 }
258
259 mutex_lock(&pool->threads_mutex);
260 bool threads_still_running = pool->thread_count > 0;
261 mutex_unlock(&pool->threads_mutex);
262 if (threads_still_running) {
263 // A timed-out thread still owns access to this pool. Retain the pool and
264 // its synchronization objects so that worker cannot race freed memory.
265 log_error("Keeping thread pool '%s' alive because %zu worker thread(s) "
266 "have not exited",
267 pool->name, pool->thread_count);
268 return;
269 }
270
271 // Clean up work queue (in case there's pending work)
272 if (pool->is_work_queue_mode) {
273 mutex_lock(&pool->work_queue_mutex);
275 while (entry) {
276 thread_pool_work_entry_t *next = entry->next;
277 SAFE_FREE(entry);
278 entry = next;
279 }
280 pool->work_queue = NULL;
281 mutex_unlock(&pool->work_queue_mutex);
282
283 // Destroy condition variable and work queue mutex
284 cond_destroy(&pool->work_available);
285 mutex_destroy(&pool->work_queue_mutex);
286 }
287
288 // Destroy threads mutex
289 mutex_destroy(&pool->threads_mutex);
290
291 NAMED_UNREGISTER(pool);
292
293 // Free pool
294 log_debug("About to free thread pool '%s' at %p", pool->name, (void *)pool);
295 SAFE_FREE(pool);
296
297 log_debug("Thread pool destroyed (freed memory)");
298}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
struct thread_pool_work_entry * next
Linked list next pointer.
struct thread_pool_work_entry thread_pool_work_entry_t
One queued function call waiting for a thread-pool worker.

References thread_pool::is_work_queue_mode, log_debug, log_error, thread_pool::name, NAMED_UNREGISTER, thread_pool_work_entry::next, SAFE_FREE, thread_pool::thread_count, thread_pool_stop_all(), thread_pool::threads, thread_pool::threads_mutex, thread_pool::work_available, thread_pool::work_queue, and thread_pool::work_queue_mutex.

Referenced by acds_server_shutdown(), client_connection_destroy(), network_server_destroy(), thread_pool_create_with_workers(), and websocket_server_destroy().

◆ thread_pool_get_count()

size_t thread_pool_get_count ( const thread_pool_t * pool)

Get thread count in the pool.

Thread-safe count of active threads in the pool.

Parameters
poolThread pool to query
Returns
Number of threads in pool, or 0 if pool is NULL

Definition at line 534 of file thread_pool.c.

534 {
535 if (!pool) {
536 return 0;
537 }
538
539 // Note: We're not locking here for performance
540 // thread_count is a simple size_t which should be atomic on most platforms
541 // If strict thread safety is required, use mutex_lock/unlock
542 return pool->thread_count;
543}

References thread_pool::thread_count.

Referenced by thread_pool_has_threads().

◆ thread_pool_has_threads()

bool thread_pool_has_threads ( const thread_pool_t * pool)

Check if pool has any threads.

Convenience function equivalent to thread_pool_get_count(pool) > 0.

Parameters
poolThread pool to check
Returns
true if pool has threads, false if empty or NULL

Definition at line 545 of file thread_pool.c.

545 {
546 return thread_pool_get_count(pool) > 0;
547}
size_t thread_pool_get_count(const thread_pool_t *pool)
Get thread count in the pool.

References thread_pool_get_count().

◆ thread_pool_interrupt_all()

asciichat_error_t thread_pool_interrupt_all ( thread_pool_t * pool,
int sig )

Send a signal to all threads in the pool.

Sends the specified signal to every thread in the pool. This is used to interrupt threads that are blocked in system calls (e.g., recv(), connect()) so they unblock and can check the global exit flag.

Thread-safe: acquires threads_mutex to iterate the thread list. Not async-signal-safe: cannot be called from signal handlers.

On POSIX systems, uses pthread_kill() to send the signal. On Windows, this is a no-op (pthread_kill is not available, but socket_shutdown() is sufficient for Windows socket unblocking).

Typically used with SIGUSR1 (which should have a registered no-op handler) or another signal that the threads are prepared to handle gracefully.

Parameters
poolThread pool to interrupt
sigSignal number to send (e.g., SIGUSR1)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 549 of file thread_pool.c.

549 {
550 if (!pool) {
551 return SET_ERRNO(ERROR_INVALID_PARAM, "pool is NULL");
552 }
553
554#ifndef _WIN32
555 // Only available on POSIX systems (Unix/Linux/macOS)
556 mutex_lock(&pool->threads_mutex);
557
558 if (pool->thread_count == 0) {
559 mutex_unlock(&pool->threads_mutex);
560 log_debug("Thread pool '%s' has no threads to interrupt", pool->name);
561 return ASCIICHAT_OK;
562 }
563
564 log_debug("Sending signal %d to %zu threads in pool '%s'", sig,
565 pool->thread_count, pool->name);
566
567 // Iterate through all threads and send signal
568 thread_pool_entry_t *entry = pool->threads;
569 int sent_count = 0;
570 int failed_count = 0;
571
572 while (entry) {
573 // pthread_kill returns 0 on success, non-zero error code on failure
574 if (pthread_kill(entry->thread, sig) != 0) {
575 log_warn("Failed to send signal %d to thread '%s' in pool '%s'", sig,
576 entry->name, pool->name);
577 failed_count++;
578 } else {
579 sent_count++;
580 }
581 entry = entry->next;
582 }
583
584 mutex_unlock(&pool->threads_mutex);
585
586 log_debug("Sent signal %d to %d/%zu threads in pool '%s' (%d failures)", sig,
587 sent_count, pool->thread_count, pool->name, failed_count);
588
589 if (failed_count > 0 && sent_count == 0) {
590 return SET_ERRNO(ERROR_THREAD,
591 "Failed to send signal to any threads in pool '%s'",
592 pool->name);
593 }
594
595 return ASCIICHAT_OK;
596#else
597 // Windows: no pthread_kill equivalent needed - socket_shutdown() is
598 // sufficient
599 (void)sig; // Unused on Windows
600 log_debug("no-op on Windows (socket shutdown is sufficient)");
601 return ASCIICHAT_OK;
602#endif
603}
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_THREAD, log_debug, log_warn, thread_pool::name, thread_pool_entry::name, thread_pool_entry::next, SET_ERRNO, thread_pool_entry::thread, thread_pool::thread_count, thread_pool::threads, and thread_pool::threads_mutex.

◆ thread_pool_queue_work()

asciichat_error_t thread_pool_queue_work ( const char * name,
thread_pool_t * pool,
void *(* work_func )(void *),
void * work_arg )

Queue a named work item to a work queue pool.

Adds a named work item to the pool's work queue. One of the pre-created worker threads will pick up the work and execute it. This function is only valid for pools created with thread_pool_create_with_workers(). The work is automatically registered with the debug naming system.

Safe to call from callback context (e.g., LWS callbacks). Work is queued without creating new threads.

Parameters
nameDebug name for the work item
poolThread pool to queue work to (must be in work queue mode)
work_funcFunction to execute
work_argArgument passed to work function
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 300 of file thread_pool.c.

302 {
303 if (!name) {
304 return SET_ERRNO(ERROR_INVALID_PARAM, "work name is required");
305 }
306
307 if (!pool) {
308 return SET_ERRNO(ERROR_INVALID_PARAM, "pool is NULL");
309 }
310
311 if (!pool->is_work_queue_mode) {
312 return SET_ERRNO(
314 "Pool not in work queue mode. Use thread_pool_create_with_workers()");
315 }
316
317 if (!work_func) {
318 return SET_ERRNO(ERROR_INVALID_PARAM, "work_func is NULL");
319 }
320
321 // Allocate work entry
324 if (!entry) {
325 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate work entry");
326 }
327
328 entry->work_func = work_func;
329 entry->work_arg = work_arg;
330 entry->next = NULL;
331
332 // Register work with debug naming system
333 NAMED_REGISTER_THREADPOOL_WORK(entry, name, NULL);
334
335 // Add to work queue (at the end)
336 mutex_lock(&pool->work_queue_mutex);
337
338 // Find the last entry in the queue
339 if (!pool->work_queue) {
340 pool->work_queue = entry;
341 } else {
343 while (last->next) {
344 last = last->next;
345 }
346 last->next = entry;
347 }
348
349 // Signal workers that work is available (WHILE HOLDING MUTEX to prevent lost
350 // wakeup race)
351 cond_signal(&pool->work_available);
352
353 mutex_unlock(&pool->work_queue_mutex);
354
355 log_dev("Queued work to pool '%s' (workers=%zu)", pool->name,
356 pool->num_workers);
357 return ASCIICHAT_OK;
358}
#define NAMED_REGISTER_THREADPOOL_WORK(work, name, parent_ptr)
Register a thread pool work item with automatic format specifier.
@ ERROR_INVALID_STATE
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
void * work_arg
Argument passed to work function.
void *(* work_func)(void *)
Work function to execute.

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, thread_pool::is_work_queue_mode, log_dev, thread_pool::name, NAMED_REGISTER_THREADPOOL_WORK, thread_pool_work_entry::next, thread_pool::num_workers, SAFE_MALLOC, SET_ERRNO, thread_pool_work_entry::work_arg, thread_pool::work_available, thread_pool_work_entry::work_func, thread_pool::work_queue, and thread_pool::work_queue_mutex.

◆ thread_pool_spawn()

asciichat_error_t thread_pool_spawn ( thread_pool_t * pool,
void *(* thread_func )(void *),
void * thread_arg,
int stop_id,
const char * thread_name )

Spawn a worker thread in the pool.

Creates and tracks a new worker thread with optional ordered cleanup. Threads are inserted into the pool's linked list in sorted order by stop_id (ascending). When the pool is stopped, threads with lower stop_id values are stopped first.

Stop ID Ordering Guidelines:

  • stop_id < 0: Unordered (stopped last, order undefined)
  • stop_id = 0: General background workers
  • stop_id = 1: Data source threads (e.g., receive, capture)
  • stop_id = 2: Processing threads (e.g., render, encode)
  • stop_id = 3: Data sink threads (e.g., send, write)

Example (Server Per-Client Threads):

  • stop_id=1: Receive thread (stop first to prevent new data)
  • stop_id=2: Render threads (stop after receive)
  • stop_id=3: Send thread (stop last after all processing)
Parameters
poolThread pool to spawn into
thread_funcThread function to execute
thread_argArgument passed to thread function
stop_idCleanup order (-1=unordered, 0+=ordered)
thread_nameThread name for debugging (max 63 chars, NULL=auto-generate)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 360 of file thread_pool.c.

363 {
364 if (!pool) {
365 return SET_ERRNO(ERROR_INVALID_PARAM, "pool is NULL");
366 }
367
368 if (pool->is_work_queue_mode) {
369 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot spawn threads in work queue "
370 "mode. Use thread_pool_queue_work()");
371 }
372
373 if (!thread_func) {
374 return SET_ERRNO(ERROR_INVALID_PARAM, "thread_func is NULL");
375 }
376
377 // Allocate thread entry
378 thread_pool_entry_t *entry =
380 if (!entry) {
381 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate thread pool entry");
382 }
383
384 memset(entry, 0, sizeof(*entry));
385 entry->stop_id = stop_id;
386 entry->thread_func = thread_func;
387 entry->thread_arg = thread_arg;
388 entry->next = NULL;
389
390 // Copy thread name (truncate if necessary)
391 if (thread_name) {
392 SAFE_STRNCPY(entry->name, thread_name, sizeof(entry->name));
393 } else {
394 // Auto-generate name
395 SAFE_SNPRINTF(entry->name, sizeof(entry->name), "%s_worker_%d", pool->name,
396 stop_id);
397 }
398
399 // Create thread
400 if (platform_thread_create(&entry->thread, entry->name, thread_func,
401 thread_arg) != 0) {
402 // Save name before freeing entry
403 char thread_name_copy[THREAD_POOL_THREAD_NAME_COPY_BUFFER_SIZE];
404 SAFE_STRNCPY(thread_name_copy, entry->name, sizeof(thread_name_copy));
405 SAFE_FREE(entry);
406 return SET_ERRNO(ERROR_THREAD, "Failed to create thread '%s' in pool '%s'",
407 thread_name_copy, pool->name);
408 }
409
410 // Add to thread list (sorted by stop_id)
411 mutex_lock(&pool->threads_mutex);
412
413 if (!pool->threads || pool->threads->stop_id > stop_id) {
414 // Insert at head
415 entry->next = pool->threads;
416 pool->threads = entry;
417 } else {
418 // Find insertion point (maintain sorted order by stop_id)
419 thread_pool_entry_t *prev = pool->threads;
420 while (prev->next && prev->next->stop_id <= stop_id) {
421 prev = prev->next;
422 }
423 entry->next = prev->next;
424 prev->next = entry;
425 }
426
427 pool->thread_count++;
428 mutex_unlock(&pool->threads_mutex);
429
430 log_debug("Spawned thread '%s' (stop_id=%d) in pool '%s' (total_threads=%zu)",
431 entry->name, stop_id, pool->name, pool->thread_count);
432
433 return ASCIICHAT_OK;
434}
#define THREAD_POOL_THREAD_NAME_COPY_BUFFER_SIZE
Definition thread_pool.c:7

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, ERROR_THREAD, thread_pool::is_work_queue_mode, log_debug, thread_pool::name, thread_pool_entry::name, thread_pool_entry::next, SAFE_FREE, SAFE_MALLOC, SAFE_SNPRINTF, SAFE_STRNCPY, SET_ERRNO, thread_pool_entry::stop_id, thread_pool_entry::thread, thread_pool_entry::thread_arg, thread_pool::thread_count, thread_pool_entry::thread_func, THREAD_POOL_THREAD_NAME_COPY_BUFFER_SIZE, thread_pool::threads, and thread_pool::threads_mutex.

Referenced by acds_server_init(), audio_sender_init(), audio_start_thread(), capture_start_thread(), client_protocol_start(), keepalive_start_thread(), and server_main().

◆ thread_pool_stop_all()

asciichat_error_t thread_pool_stop_all ( thread_pool_t * pool)

Stop all threads in the pool in stop_id order.

Joins all threads in ascending stop_id order (lower values first). Threads with negative stop_id are stopped last in undefined order. This function blocks until all threads have exited.

Shutdown Sequence:

  1. Threads with stop_id >= 0 are joined in ascending order
  2. Threads with stop_id < 0 are joined in any order
  3. All thread entries are freed

After this call, the pool is empty but still valid - you can spawn new threads or destroy the pool.

Parameters
poolThread pool to stop
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 436 of file thread_pool.c.

436 {
437 if (!pool) {
438 return SET_ERRNO(ERROR_INVALID_PARAM, "pool is NULL");
439 }
440
441 mutex_lock(&pool->threads_mutex);
442
443 if (pool->thread_count == 0) {
444 mutex_unlock(&pool->threads_mutex);
445 log_debug("Thread pool '%s' has no threads to stop", pool->name);
446 return ASCIICHAT_OK;
447 }
448
449 log_debug("Stopping %zu threads in pool '%s' in stop_id order",
450 pool->thread_count, pool->name);
451
452 // For work queue mode, signal workers to shutdown (BEFORE releasing the mutex
453 // to prevent new work)
454 if (pool->is_work_queue_mode) {
455 mutex_lock(&pool->work_queue_mutex);
456 pool->shutdown_requested = true;
457 cond_broadcast(&pool->work_available);
458 mutex_unlock(&pool->work_queue_mutex);
459 }
460
461 // Detach the current list so workers can finish without holding the pool
462 // mutex. Any thread that misses its join deadline is reinserted below.
463 thread_pool_entry_t *threads_to_join = pool->threads;
464 pool->threads = NULL;
465 pool->thread_count = 0;
466
467 // Release mutex BEFORE joining threads to prevent deadlock if workers need to
468 // acquire it
469 mutex_unlock(&pool->threads_mutex);
470
471 // Now join threads (WITHOUT holding the mutex to prevent deadlock)
472 thread_pool_entry_t *entry = threads_to_join;
473 int joined_count = 0, freed_count = 0, still_running_count = 0;
474 thread_pool_entry_t *still_running = NULL;
475 const uint64_t THREAD_JOIN_TIMEOUT_NS =
476 2 * 1000000000ULL; // 2 second timeout per thread
477
478 while (entry) {
479 log_debug("Joining thread '%s' (stop_id=%d) in pool '%s' with 2s timeout",
480 entry->name, entry->stop_id, pool->name);
481 thread_pool_entry_t *next = entry->next;
482
483 // A timed-out worker may still access its pool and arguments. Keep its
484 // entry tracked so later shutdown can join it before freeing those objects.
485 int join_result =
486 thread_join_timeout(&entry->thread, NULL, THREAD_JOIN_TIMEOUT_NS);
487 if (join_result != 0) {
488 if (join_result == ETIMEDOUT) {
489 log_warn("Thread '%s' (stop_id=%d) did not exit within 2s timeout; "
490 "retaining its pool entry.",
491 entry->name, entry->stop_id);
492 } else {
493 log_error("Failed to join thread '%s' in pool '%s' (error %d); "
494 "retaining its pool entry",
495 entry->name, pool->name, join_result);
496 }
497 entry->next = still_running;
498 still_running = entry;
499 still_running_count++;
500 entry = next;
501 continue;
502 } else {
503 joined_count++;
504 }
505
506 log_debug("Freeing thread_pool_entry '%s' at %p", entry->name,
507 (void *)entry);
508 SAFE_FREE(entry);
509 freed_count++;
510 entry = next;
511 }
512
513 if (still_running) {
514 mutex_lock(&pool->threads_mutex);
515 while (still_running) {
516 thread_pool_entry_t *entry = still_running;
517 still_running = still_running->next;
518 entry->next = NULL;
519 thread_pool_insert_entry_locked(pool, entry);
520 }
521 mutex_unlock(&pool->threads_mutex);
522 }
523
524 log_debug("joined=%d, freed=%d", joined_count, freed_count);
525
526 log_debug("All threads stopped in pool '%s'", pool->name);
527 if (still_running_count > 0) {
528 return SET_ERRNO(ERROR_THREAD, "%d thread(s) in pool '%s' did not stop",
529 still_running_count, pool->name);
530 }
531 return ASCIICHAT_OK;
532}
unsigned long long uint64_t

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_THREAD, thread_pool::is_work_queue_mode, log_debug, log_error, log_warn, thread_pool::name, thread_pool_entry::name, thread_pool_entry::next, SAFE_FREE, SET_ERRNO, thread_pool::shutdown_requested, thread_pool_entry::stop_id, thread_pool_entry::thread, thread_pool::thread_count, thread_pool::threads, thread_pool::threads_mutex, thread_pool::work_available, and thread_pool::work_queue_mutex.

Referenced by network_server_stop(), and thread_pool_destroy().