Nilorea Library thread pool api example.
#include <stdio.h>
#include <errno.h>
#include <string.h>
void usage(void) {
fprintf(stderr,
" -v version\n"
" -h help\n"
" -V LOG_LEVEL (LOG_DEBUG,INFO,NOTICE,ERR)\n");
}
void process_args(int argc, char** argv) {
int getoptret = 0,
while ((getoptret = getopt(argc, argv, "vhV:")) != EOF) {
switch (getoptret) {
case 'v':
fprintf(stderr, "Date de compilation : %s a %s.\n", __DATE__, __TIME__);
exit(1);
case 'V':
if (!strncmp("LOG_NULL", optarg, 5)) {
} else {
if (!strncmp("LOG_NOTICE", optarg, 6)) {
} else {
if (!strncmp("LOG_INFO", optarg, 7)) {
} else {
if (!strncmp("LOG_ERR", optarg, 5)) {
} else {
if (!strncmp("LOG_DEBUG", optarg, 5)) {
} else {
fprintf(stderr, "%s n'est pas un niveau de log valide.\n", optarg);
exit(-1);
}
}
}
}
}
break;
default:
case '?': {
if (optopt == 'V') {
fprintf(stderr, "\n Missing log level\n");
}
usage();
exit(1);
}
case 'h': {
usage();
exit(1);
}
}
}
}
void* occupy_thread(void* rest) {
intptr_t sleep_value = (intptr_t)(rest);
n_log(
LOG_DEBUG,
"Starting to sleep %d usecs on thread %lld", sleep_value, pthread_self());
if (sleep_value < 1000000) {
usleep(sleep_value);
} else {
usleep((sleep_value) % 1000000);
sleep((sleep_value / 1000000));
}
n_log(
LOG_DEBUG,
"End of sleep %d usecs on thread %lld", sleep_value, pthread_self());
return NULL;
}
int main(int argc, char** argv) {
int nb_waiting_threads = 2 * nb_active_threads;
int nb_total_threads = (nb_active_threads + nb_waiting_threads);
process_args(argc, argv);
n_log(
LOG_INFO,
"Creating a new thread pool of %d active and %d waiting threads", nb_active_threads, nb_waiting_threads);
for (int it = 0; it < nb_total_threads; it++) {
int sleep_value = 1 + rand() % 1000000;
n_log(
LOG_ERR,
"Error adding client management to thread pool");
}
}
n_log(
LOG_INFO,
"Adding tasks done. Waiting for pool thread to complete the tasks...");
exit(0);
}
#define __n_assert(__ptr, __ret)
macro to assert things
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_DEBUG
debug-level messages
#define LOG_ERR
error conditions
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
#define LOG_NOTICE
normal but significant condition
#define LOG_NULL
no log output
#define LOG_INFO
informational
THREAD_POOL * new_thread_pool(size_t nbmaxthr, size_t nb_max_waiting)
Create a new pool of nbmaxthr threads.
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
int destroy_threaded_pool(THREAD_POOL **pool, unsigned int delay)
delete a thread_pool, exit the threads and free the structs
long int get_nb_cpu_cores()
get number of core of current system
#define DIRECT_PROC
processing mode for added func, direct start
int wait_for_threaded_pool(THREAD_POOL *thread_pool, unsigned int delay)
Wait for all the launched process in the thread pool to terminate.
Structure of a trhead pool.