Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
n_thread_pool.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
28#include <unistd.h>
29#include "nilorea/n_common.h"
30#include "nilorea/n_log.h"
32#include "nilorea/n_time.h"
33
34#ifdef __linux__
35#include <sys/sysinfo.h>
36#endif
37#include <pthread.h>
38#include <string.h>
39#include <errno.h>
40
45long int get_nb_cpu_cores() {
46 long int nb_procs = 0;
47#ifdef __windows__
48 SYSTEM_INFO sysinfo;
49 GetSystemInfo(&sysinfo);
50 nb_procs = (long int)sysinfo.dwNumberOfProcessors;
51#else
52 nb_procs = sysconf(_SC_NPROCESSORS_ONLN);
53#endif
54 return nb_procs;
55}
56
63 THREAD_POOL_NODE* node = (THREAD_POOL_NODE*)param;
64
65 if (!node) {
66 n_log(LOG_ERR, "Thread fatal error, no valid payload found, exiting thread function !");
67 pthread_exit(NULL);
68 return NULL;
69 }
70
71 n_log(LOG_DEBUG, "Thread %ld started", node->thr);
72
73 int thread_state = 0;
74 do {
75 n_log(LOG_DEBUG, "Thread pool processing func waiting");
76
77 // note: direct procs will automatically post th_start
78 sem_wait(&node->th_start);
79
80 pthread_mutex_lock(&node->lock);
81 thread_state = node->thread_state;
82 pthread_mutex_unlock(&node->lock);
83
84 if (thread_state == RUNNING_THREAD) {
85 n_log(LOG_DEBUG, "Thread pool running proc %p", node->func);
86 void* (*func_to_run)(void* param) = NULL;
87 void* param_to_run = NULL;
88 pthread_mutex_lock(&node->lock);
89 node->state = RUNNING_PROC;
90 func_to_run = node->func;
91 param_to_run = node->param;
92 pthread_mutex_unlock(&node->lock);
93
94 if (func_to_run) {
95 func_to_run(param_to_run);
96 }
97 n_log(LOG_DEBUG, "Thread pool end proc %p", func_to_run);
98
99 pthread_mutex_lock(&node->lock);
100 node->func = NULL;
101 node->param = NULL;
102 node->state = IDLE_PROC;
103 int type = node->type;
104 node->type = -1;
105 // NORMAL_PROC or DIRECT_PROC do not need to post th_end
106 if (type & SYNCED_PROC)
107 sem_post(&node->th_end);
108 pthread_mutex_unlock(&node->lock);
109
111 }
112 } while (thread_state != EXITING_THREAD);
113
114 n_log(LOG_DEBUG, "Thread %ld exiting...", node->thr);
115
116 pthread_mutex_lock(&node->lock);
118 pthread_mutex_unlock(&node->lock);
119
120 n_log(LOG_DEBUG, "Thread %ld exited", node->thr);
121
122 pthread_exit(NULL);
123
124 return NULL;
125} /* thread_pool_processing_function */
126
133THREAD_POOL* new_thread_pool(size_t nbmaxthr, size_t nb_max_waiting) {
134 THREAD_POOL* thread_pool = NULL;
135
137 if (!thread_pool)
138 return NULL;
139
140 thread_pool->max_threads = nbmaxthr;
141 thread_pool->nb_max_waiting = nb_max_waiting;
143
144 thread_pool->thread_list = (THREAD_POOL_NODE**)malloc(nbmaxthr * sizeof(THREAD_POOL_NODE*));
145 if (!thread_pool->thread_list) {
147 return NULL;
148 }
149
152 n_log(LOG_ERR, "Unable to initialize wait list");
155 return NULL;
156 }
157
158 pthread_mutex_init(&thread_pool->lock, NULL);
159
160 if (sem_init(&thread_pool->nb_tasks, 0, 1) == -1) {
161 int error = errno;
162 n_log(LOG_ERR, "sem_init failed : %s on &thread_pool -> nb_tasks", strerror(error));
164 pthread_mutex_destroy(&thread_pool->lock);
167 return NULL;
168 }
169
170 size_t it = 0;
171 for (it = 0; it < nbmaxthr; it++) {
173 thread_pool->thread_list[it]->type = -1;
177
178 if (sem_init(&thread_pool->thread_list[it]->th_start, 0, 0) == -1) {
179 int error = errno;
180 n_log(LOG_ERR, "sem_init failed : %s on &thread_pool -> thread_list[ %zu ] -> th_start", strerror(error), it);
182 goto cleanup_error;
183 }
184 if (sem_init(&thread_pool->thread_list[it]->th_end, 0, 0) == -1) {
185 int error = errno;
186 n_log(LOG_ERR, "sem_init failed : %s on &thread_pool -> thread_list[ %zu] -> th_end", strerror(error), it);
187 sem_destroy(&thread_pool->thread_list[it]->th_start);
189 goto cleanup_error;
190 }
191
192 thread_pool->thread_list[it]->func = NULL;
193 thread_pool->thread_list[it]->param = NULL;
194
195 pthread_mutex_init(&thread_pool->thread_list[it]->lock, NULL);
196
197 if (pthread_create(&thread_pool->thread_list[it]->thr, NULL, thread_pool_processing_function, (void*)thread_pool->thread_list[it]) != 0) {
198 n_log(LOG_ERR, "pthread_create failed : %s for it %zu", strerror(errno), it);
199 pthread_mutex_destroy(&thread_pool->thread_list[it]->lock);
200 sem_destroy(&thread_pool->thread_list[it]->th_start);
201 sem_destroy(&thread_pool->thread_list[it]->th_end);
203 goto cleanup_error;
204 }
205 }
206 return thread_pool;
207
208cleanup_error:
209 for (size_t j = 0; j < it; j++) {
210 pthread_mutex_lock(&thread_pool->thread_list[j]->lock);
212 sem_post(&thread_pool->thread_list[j]->th_start);
213 pthread_mutex_unlock(&thread_pool->thread_list[j]->lock);
214 pthread_join(thread_pool->thread_list[j]->thr, NULL);
215 pthread_mutex_destroy(&thread_pool->thread_list[j]->lock);
216 sem_destroy(&thread_pool->thread_list[j]->th_start);
217 sem_destroy(&thread_pool->thread_list[j]->th_end);
219 }
221 sem_destroy(&thread_pool->nb_tasks);
222 pthread_mutex_destroy(&thread_pool->lock);
225 return NULL;
226} /* new_thread_pool */
227
236int add_threaded_process(THREAD_POOL* thread_pool, void* (*func_ptr)(void* param), void* param, int mode) {
237 if (!thread_pool) {
238 n_log(LOG_ERR, "thread_pool is not allocated, can't add processes to it !");
239 return FALSE;
240 }
241
242 if (!thread_pool->thread_list) {
243 n_log(LOG_ERR, "thread_pool thread_list is not allocated, can't add processes to it !");
244 return FALSE;
245 }
246
247 /* validate that exactly one of NORMAL_PROC, SYNCED_PROC, DIRECT_PROC is set */
248 int proc_mode = mode & (NORMAL_PROC | SYNCED_PROC | DIRECT_PROC);
249 if (proc_mode != NORMAL_PROC && proc_mode != SYNCED_PROC && proc_mode != DIRECT_PROC) {
250 n_log(LOG_ERR, "invalid mode %d: exactly one of NORMAL_PROC, SYNCED_PROC, DIRECT_PROC must be set", mode);
251 return FALSE;
252 }
253
254 if (!(mode & NO_LOCK)) pthread_mutex_lock(&thread_pool->lock);
255
256 size_t it = 0;
257 while (it < thread_pool->max_threads) {
258 pthread_mutex_lock(&thread_pool->thread_list[it]->lock);
260 break;
261 }
262 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
263 it++;
264 }
265 // we have a free thread slot, and the lock on it
266 if (it < thread_pool->max_threads) {
268 thread_pool->thread_list[it]->func = func_ptr;
269 thread_pool->thread_list[it]->param = param;
272 } else {
273 n_log(LOG_ERR, "unknown mode %d for thread %zu", mode, it);
274 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
275 if (!(mode & NO_LOCK))
276 pthread_mutex_unlock(&thread_pool->lock);
277 return FALSE;
278 }
279 if (mode & NORMAL_PROC || mode & DIRECT_PROC)
280 sem_post(&thread_pool->thread_list[it]->th_start);
281 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
282 n_log(LOG_DEBUG, "proc %p(%p) added on thread %zu", func_ptr, param, it);
283 } else {
284 // all thread are occupied -> test waiting lists. not holding thread_list[ it ] lock because it was obligatory unlocked before
285
286 // if already coming from queue, or if it should be part of a synced start, do not re-add && return FALSE
287 // it's only an error if SYNCED_PROC mode
288 int cancel_and_return = FALSE;
289 if (mode & NO_QUEUE) {
290 n_log(LOG_DEBUG, "Thread pool active threads are all busy and mode is NO_QUEUE, cannot add %p(%p) to pool %p", func_ptr, param, thread_pool);
291 cancel_and_return = TRUE;
292 } else if (mode & SYNCED_PROC) {
293 n_log(LOG_ERR, "Thread pool active threads are all busy, cannot add SYNCED_PROC %p(%p) to pool %p", func_ptr, param, thread_pool);
294 cancel_and_return = TRUE;
295 } else if (mode & DIRECT_PROC) {
296 n_log(LOG_ERR, "Thread pool active threads are all busy, cannot add DIRECT_PROC %p(%p) to pool %p", func_ptr, param, thread_pool);
297 cancel_and_return = TRUE;
298 }
299
300 if (cancel_and_return) {
301 if (!(mode & NO_LOCK))
302 pthread_mutex_unlock(&thread_pool->lock);
303 return FALSE;
304 }
305
306 // try adding to wait list
308 THREAD_WAITING_PROC* proc = NULL;
309 Malloc(proc, THREAD_WAITING_PROC, 1);
310 if (!proc) {
311 n_log(LOG_ERR, "Failed to allocate THREAD_WAITING_PROC");
312 if (!(mode & NO_LOCK)) pthread_mutex_unlock(&thread_pool->lock);
313 return FALSE;
314 }
315 proc->func = func_ptr;
316 proc->param = param;
317 list_push(thread_pool->waiting_list, proc, free);
318 n_log(LOG_DEBUG, "Adding %p %p to waitlist", proc->func, proc->param);
319 } else {
320 n_log(LOG_ERR, "proc %p(%p) was dropped from waitlist because waitlist of thread pool %p is full", func_ptr, param, thread_pool);
321 if (!(mode & NO_LOCK)) pthread_mutex_unlock(&thread_pool->lock);
322 return FALSE;
323 }
324 }
325
326 /* consume idle signal: pool now has work in progress */
327 if (sem_trywait(&thread_pool->nb_tasks) != 0 && errno != EAGAIN) {
328 int error = errno;
329 n_log(LOG_ERR, "sem_trywait nb_tasks error in thread_pool %p: %s", thread_pool, strerror(error));
330 }
331
332 if (!(mode & NO_LOCK)) pthread_mutex_unlock(&thread_pool->lock);
333
334 return TRUE;
335} /* add_threaded_process */
336
343 if (!thread_pool)
344 return FALSE;
345
347 return FALSE;
348
349 int retval = TRUE;
350
351 pthread_mutex_lock(&thread_pool->lock);
352 for (size_t it = 0; it < thread_pool->max_threads; it++) {
353 int to_run = 0;
354 pthread_mutex_lock(&thread_pool->thread_list[it]->lock);
356 to_run = 1;
357 }
358 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
359 if (to_run == 1) {
360 if (sem_post(&thread_pool->thread_list[it]->th_start) != 0) {
361 int error = errno;
362 n_log(LOG_ERR, "sem_post th_start error in thread_pool %p , thread_list[ %zu ] : %s", thread_pool, it, strerror(error));
363 retval = FALSE;
364 }
365 }
366 }
367 pthread_mutex_unlock(&thread_pool->lock);
368
369 return retval;
370} /* start_threaded_pool */
371
378 __n_assert(thread_pool, return FALSE);
379 __n_assert(thread_pool->thread_list, return FALSE);
380
381 int retval = TRUE;
382 for (size_t it = 0; it < thread_pool->max_threads; it++) {
383 int is_synced = 0;
384 pthread_mutex_lock(&thread_pool->thread_list[it]->lock);
386 is_synced = 1;
387 }
388 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
389
390 if (is_synced) {
391 if (sem_wait(&thread_pool->thread_list[it]->th_end) == -1) {
392 int error = errno;
393 n_log(LOG_ERR, "sem_wait th_end error in thread_pool %p , thread_list[ %zu ] : %s", thread_pool, it, strerror(error));
394 retval = FALSE;
395 }
396 }
397 }
398 return retval;
399} /* wait_for_synced_threaded_pool */
400
407 __n_assert(thread_pool, return FALSE);
408 __n_assert(thread_pool->thread_list, return FALSE);
409
410 /* kick off draining the wait list before blocking */
412
413 while (sem_wait(&thread_pool->nb_tasks) == -1) {
414 int error = errno;
415 if (error == EINTR) {
416 continue;
417 }
418 n_log(LOG_ERR, "sem_wait nb_tasks error in thread_pool %p: %s", thread_pool, strerror(error));
419 return FALSE;
420 }
421 /* restore the idle signal so it can be waited on again or checked */
422 sem_post(&thread_pool->nb_tasks);
423 return TRUE;
424} /* wait_for_threaded_pool */
425
432int destroy_threaded_pool(THREAD_POOL** pool, unsigned int delay) {
433 __n_assert(pool && (*pool), return FALSE);
434 __n_assert((*pool)->thread_list, return FALSE);
435
436 int DONE = 0;
437 int max_retries = 1000;
438
439 while (!DONE) {
440 DONE = 1;
441 pthread_mutex_lock(&(*pool)->lock);
442 for (size_t it = 0; it < (*pool)->max_threads; it++) {
443 pthread_mutex_lock(&(*pool)->thread_list[it]->lock);
444 int state = (*pool)->thread_list[it]->state;
445 int thread_state = (*pool)->thread_list[it]->thread_state;
446 pthread_mutex_unlock(&(*pool)->thread_list[it]->lock);
447
448 if (thread_state == EXITING_THREAD || thread_state == EXITED_THREAD) {
449 continue;
450 }
451
452 if (state == IDLE_PROC) {
453 pthread_mutex_lock(&(*pool)->thread_list[it]->lock);
454 (*pool)->thread_list[it]->thread_state = EXITING_THREAD;
455 sem_post(&(*pool)->thread_list[it]->th_start);
456 pthread_mutex_unlock(&(*pool)->thread_list[it]->lock);
457 } else {
458 DONE = 0;
459 }
460 }
461 pthread_mutex_unlock(&(*pool)->lock);
462
463 if (!DONE) {
464 max_retries--;
465 if (max_retries <= 0) {
466 pthread_mutex_lock(&(*pool)->lock);
467 for (size_t it = 0; it < (*pool)->max_threads; it++) {
468 pthread_mutex_lock(&(*pool)->thread_list[it]->lock);
469 if ((*pool)->thread_list[it]->thread_state != EXITING_THREAD && (*pool)->thread_list[it]->thread_state != EXITED_THREAD) {
470 (*pool)->thread_list[it]->thread_state = EXITING_THREAD;
471 sem_post(&(*pool)->thread_list[it]->th_start);
472 }
473 pthread_mutex_unlock(&(*pool)->thread_list[it]->lock);
474 }
475 pthread_mutex_unlock(&(*pool)->lock);
476 break;
477 }
478 }
479
480 u_sleep(delay);
481 }
482
483 /* join threads without holding pool lock to avoid deadlock:
484 * threads may call refresh_thread_pool() which needs pool->lock */
485 for (size_t it = 0; it < (*pool)->max_threads; it++) {
486 pthread_join((*pool)->thread_list[it]->thr, NULL);
487 }
488
489 /* all threads have exited, safe to clean up without locking */
490 for (size_t it = 0; it < (*pool)->max_threads; it++) {
491 pthread_mutex_destroy(&(*pool)->thread_list[it]->lock);
492 sem_destroy(&(*pool)->thread_list[it]->th_start);
493 sem_destroy(&(*pool)->thread_list[it]->th_end);
494 Free((*pool)->thread_list[it]);
495 }
496 Free((*pool)->thread_list);
497 list_destroy(&(*pool)->waiting_list);
498
499 sem_destroy(&(*pool)->nb_tasks);
500
501 pthread_mutex_destroy(&(*pool)->lock);
502
503 Free((*pool));
504
505 return TRUE;
506} /* destroy_threaded_pool */
507
514 __n_assert(thread_pool, return FALSE);
515 __n_assert(thread_pool->waiting_list, return FALSE);
516
517 /* Trying to empty the wait list */
518 int push_status = 0;
519 pthread_mutex_lock(&thread_pool->lock);
521 push_status = 1;
522 while (push_status == 1) {
524 if (node && node->ptr) {
526 if (proc) { // cppcheck-suppress knownConditionTrueFalse ; defensive check after cast
527 if (add_threaded_process(thread_pool, proc->func, proc->param, NORMAL_PROC | NO_QUEUE | NO_LOCK) == TRUE) {
528 THREAD_WAITING_PROC* procptr = NULL;
529 LIST_NODE* next_node = node->next;
531 n_log(LOG_DEBUG, "waitlist: adding %p,%p to %p", procptr->func, procptr->param, thread_pool);
532 Free(procptr);
533 (void)next_node; /* advance past removed node (consumed by next iteration) */
534 } else {
535 n_log(LOG_DEBUG, "waitlist: cannot add proc %p from waiting list of %p, all active threads are busy !", proc, thread_pool);
536 push_status = 0;
537 }
538 } else {
539 n_log(LOG_ERR, "waitlist: trying to add invalid NULL proc on thread pool %p !", thread_pool);
540 push_status = 0;
541 }
542 } else {
543 push_status = 0;
544 }
545 } // while( push_status == 1 )
546
547 // update statistics: count threads with assigned work (waiting to run or running)
549 for (size_t it = 0; it < thread_pool->max_threads; it++) {
550 pthread_mutex_lock(&thread_pool->thread_list[it]->lock);
553 pthread_mutex_unlock(&thread_pool->thread_list[it]->lock);
554 }
555
556 /* signal idle: no active/waiting threads and waiting list is empty */
558 int value = 0;
559 sem_getvalue(&thread_pool->nb_tasks, &value);
560 if (value == 0) {
561 sem_post(&thread_pool->nb_tasks);
562 }
563 }
564
565 pthread_mutex_unlock(&thread_pool->lock);
566
567 return TRUE;
568} // refresh_thread_pool()
THREAD_POOL * thread_pool
Definition ex_fluid.c:76
int DONE
Definition ex_fluid.c:58
static int mode
static NETWORK_POOL * pool
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
Definition n_common.h:204
#define __n_assert(__ptr, __ret)
macro to assert things
Definition n_common.h:279
#define Free(__ptr)
Free Handler to get errors.
Definition n_common.h:263
void * ptr
void pointer to store
Definition n_list.h:46
LIST_NODE * start
pointer to the start of the list
Definition n_list.h:66
size_t nb_items
number of item currently in the list
Definition n_list.h:61
struct LIST_NODE * next
pointer to the next node
Definition n_list.h:52
int list_push(LIST *list, void *ptr, void(*destructor)(void *ptr))
Add a pointer to the end of the list.
Definition n_list.c:228
#define remove_list_node(__LIST_, __NODE_, __TYPE_)
Remove macro helper for void pointer casting.
Definition n_list.h:98
int list_destroy(LIST **list)
Empty and Free a list container.
Definition n_list.c:548
LIST * new_generic_list(size_t max_items)
Initialiaze a generic list container to max_items pointers.
Definition n_list.c:37
#define MAX_LIST_ITEMS
flag to pass to new_generic_list for the maximum possible number of item in a list
Definition n_list.h:75
Structure of a generic list node.
Definition n_list.h:44
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:89
#define LOG_DEBUG
debug-level messages
Definition n_log.h:84
#define LOG_ERR
error conditions
Definition n_log.h:76
void u_sleep(unsigned int usec)
wrapper around usleep for API consistency
Definition n_time.c:54
size_t nb_max_waiting
Maximum number of waiting procedures in the list, 0 for unlimited.
int state
state of the proc , RUNNING_PROC when it is busy processing func( param) , IDLE_PROC when it waits fo...
int type
SYNCED or DIRECT process start.
size_t max_threads
Maximum number of running threads in the list.
void * param
if not NULL , passed as argument
void *(* func)(void *param)
function to call in the thread
sem_t th_end
thread ending semaphore
pthread_mutex_t lock
mutex to prevent mutual access of node parameters
struct THREAD_POOL * thread_pool
pointer to assigned thread pool
sem_t th_start
thread starting semaphore
pthread_t thr
thread id
THREAD_POOL_NODE ** thread_list
Dynamically allocated but fixed size thread array.
LIST * waiting_list
Waiting list handling.
size_t nb_actives
number of threads actually doing a proc
sem_t nb_tasks
semaphore signaling pool idle state: value 0 = work in progress, value 1 = pool is idle (no active th...
void *(* func)(void *param)
function to call in the thread
int thread_state
state of the managing thread , RUNNING_THREAD, EXITING_THREAD, EXITED_THREAD
pthread_mutex_t lock
mutex to prevent mutual access of waiting_list parameters
void * param
if not NULL , passed as argument
#define NORMAL_PROC
processing mode for added func, synced start, can be queued
int start_threaded_pool(THREAD_POOL *thread_pool)
Launch the process waiting for execution in the thread pool.
THREAD_POOL * new_thread_pool(size_t nbmaxthr, size_t nb_max_waiting)
Create a new pool of nbmaxthr threads.
#define EXITED_THREAD
indicate that the pool is off, all jobs have been consumed
#define SYNCED_PROC
processing mode for added func, synced start, not queued
int add_threaded_process(THREAD_POOL *thread_pool, void *(*func_ptr)(void *param), void *param, int mode)
add a function and params to a thread pool
#define NO_QUEUE
special processing mode for waiting_list: do not add the work in queue since it' coming from the queu...
int refresh_thread_pool(THREAD_POOL *thread_pool)
try to add some waiting DIRECT_PROCs on some free thread slots, else do nothing
#define IDLE_PROC
status of a thread which is waiting for some proc
int wait_for_threaded_pool(THREAD_POOL *thread_pool)
Wait for the thread pool to become idle (no active threads, empty waiting list), blocking without pol...
int destroy_threaded_pool(THREAD_POOL **pool, unsigned int delay)
delete a thread_pool, exit the threads and free the structs
int wait_for_synced_threaded_pool(THREAD_POOL *thread_pool)
wait for all the launched process, blocking but light on the CPU as there is no polling
long int get_nb_cpu_cores()
get number of core of current system
#define DIRECT_PROC
processing mode for added func, direct start, not queued
#define RUNNING_PROC
status of a thread which proc is currently running
#define NO_LOCK
if passed to add_threaded_process, skip main table lock in case we are in a func which is already loc...
#define EXITING_THREAD
indicate that the pool is exiting, unfinished jobs will finish and the pool will exit the threads and...
#define RUNNING_THREAD
indicate that the pool is running and ready to use
#define WAITING_PROC
status of a thread who have proc waiting to be processed
Structure of a thread pool.
A thread pool node.
Structure of a waiting process item.
Common headers and low-level functions & define.
Generic log system.
void * thread_pool_processing_function(void *param)
Internal thread pool processing function.
Thread pool declaration.
Timing utilities.