Fixed-size pthread pool processing job slices in C
C
#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <stddef.h>
typedef struct { int (*fn)(void *); void *arg; int err; } Job;
typedef struct { Job *jobs; size_t lo, hi; } Slice;
static void *run_slice(void *arg) {
Slice *s = arg;
for (size_t i = s->lo; i < s->hi; i++)
s->jobs[i].err = s->jobs[i].fn(s->jobs[i].arg);
return NULL;
}
int pool_run(Job *jobs, size_t n, int workers) {
pthread_t t[8]; Slice s[8];
if (workers < 1 || workers > 8) return -1;
for (int w = 0; w < workers; w++) {
s[w] = (Slice){jobs, n * w / workers, n * (w + 1) / workers};
if (pthread_create(&t[w], NULL, run_slice, &s[w])) return -1;
}
for (int w = 0; w < workers; w++) pthread_join(t[w], NULL);
return 0;
}