s3:lib/pthreadpool: fix the build on older systems
[Samba.git] / source3 / lib / pthreadpool / pthreadpool.c
blobb071e5393db5b20d86a6064a9465037f1956e3df
1 /*
2 * Unix SMB/CIFS implementation.
3 * thread pool implementation
4 * Copyright (C) Volker Lendecke 2009
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "replace.h"
21 #include "system/time.h"
22 #include "system/filesys.h"
23 #include "system/wait.h"
24 #include "system/threads.h"
25 #include "pthreadpool.h"
26 #include "lib/util/dlinklist.h"
27 #include <assert.h>
29 struct pthreadpool_job {
30 int id;
31 void (*fn)(void *private_data);
32 void *private_data;
35 struct pthreadpool {
37 * List pthreadpools for fork safety
39 struct pthreadpool *prev, *next;
42 * Control access to this struct
44 pthread_mutex_t mutex;
47 * Threads waiting for work do so here
49 pthread_cond_t condvar;
52 * Array of jobs
54 size_t jobs_array_len;
55 struct pthreadpool_job *jobs;
57 size_t head;
58 size_t num_jobs;
61 * pipe for signalling
63 int sig_pipe[2];
66 * indicator to worker threads that they should shut down
68 int shutdown;
71 * maximum number of threads
73 int max_threads;
76 * Number of threads
78 int num_threads;
81 * Number of idle threads
83 int num_idle;
86 * An array of threads that require joining.
88 int num_exited;
89 pthread_t *exited; /* We alloc more */
92 static pthread_mutex_t pthreadpools_mutex = PTHREAD_MUTEX_INITIALIZER;
93 static struct pthreadpool *pthreadpools = NULL;
94 static pthread_once_t pthreadpool_atfork_initialized = PTHREAD_ONCE_INIT;
96 static void pthreadpool_prep_atfork(void);
99 * Initialize a thread pool
102 int pthreadpool_init(unsigned max_threads, struct pthreadpool **presult)
104 struct pthreadpool *pool;
105 int ret;
107 pool = (struct pthreadpool *)malloc(sizeof(struct pthreadpool));
108 if (pool == NULL) {
109 return ENOMEM;
112 pool->jobs_array_len = 4;
113 pool->jobs = calloc(
114 pool->jobs_array_len, sizeof(struct pthreadpool_job));
116 if (pool->jobs == NULL) {
117 free(pool);
118 return ENOMEM;
121 pool->head = pool->num_jobs = 0;
123 ret = pipe(pool->sig_pipe);
124 if (ret == -1) {
125 int err = errno;
126 free(pool->jobs);
127 free(pool);
128 return err;
131 ret = pthread_mutex_init(&pool->mutex, NULL);
132 if (ret != 0) {
133 close(pool->sig_pipe[0]);
134 close(pool->sig_pipe[1]);
135 free(pool->jobs);
136 free(pool);
137 return ret;
140 ret = pthread_cond_init(&pool->condvar, NULL);
141 if (ret != 0) {
142 pthread_mutex_destroy(&pool->mutex);
143 close(pool->sig_pipe[0]);
144 close(pool->sig_pipe[1]);
145 free(pool->jobs);
146 free(pool);
147 return ret;
150 pool->shutdown = 0;
151 pool->num_threads = 0;
152 pool->num_exited = 0;
153 pool->exited = NULL;
154 pool->max_threads = max_threads;
155 pool->num_idle = 0;
157 ret = pthread_mutex_lock(&pthreadpools_mutex);
158 if (ret != 0) {
159 pthread_cond_destroy(&pool->condvar);
160 pthread_mutex_destroy(&pool->mutex);
161 close(pool->sig_pipe[0]);
162 close(pool->sig_pipe[1]);
163 free(pool->jobs);
164 free(pool);
165 return ret;
167 DLIST_ADD(pthreadpools, pool);
169 ret = pthread_mutex_unlock(&pthreadpools_mutex);
170 assert(ret == 0);
172 pthread_once(&pthreadpool_atfork_initialized, pthreadpool_prep_atfork);
174 *presult = pool;
176 return 0;
179 static void pthreadpool_prepare(void)
181 int ret;
182 struct pthreadpool *pool;
184 ret = pthread_mutex_lock(&pthreadpools_mutex);
185 assert(ret == 0);
187 pool = pthreadpools;
189 while (pool != NULL) {
190 ret = pthread_mutex_lock(&pool->mutex);
191 assert(ret == 0);
192 pool = pool->next;
196 static void pthreadpool_parent(void)
198 int ret;
199 struct pthreadpool *pool;
201 for (pool = DLIST_TAIL(pthreadpools);
202 pool != NULL;
203 pool = DLIST_PREV(pool)) {
204 ret = pthread_mutex_unlock(&pool->mutex);
205 assert(ret == 0);
208 ret = pthread_mutex_unlock(&pthreadpools_mutex);
209 assert(ret == 0);
212 static void pthreadpool_child(void)
214 int ret;
215 struct pthreadpool *pool;
217 for (pool = DLIST_TAIL(pthreadpools);
218 pool != NULL;
219 pool = DLIST_PREV(pool)) {
221 close(pool->sig_pipe[0]);
222 close(pool->sig_pipe[1]);
224 ret = pipe(pool->sig_pipe);
225 assert(ret == 0);
227 pool->num_threads = 0;
229 pool->num_exited = 0;
230 free(pool->exited);
231 pool->exited = NULL;
233 pool->num_idle = 0;
234 pool->head = 0;
235 pool->num_jobs = 0;
237 ret = pthread_mutex_unlock(&pool->mutex);
238 assert(ret == 0);
241 ret = pthread_mutex_unlock(&pthreadpools_mutex);
242 assert(ret == 0);
245 static void pthreadpool_prep_atfork(void)
247 pthread_atfork(pthreadpool_prepare, pthreadpool_parent,
248 pthreadpool_child);
252 * Return the file descriptor which becomes readable when a job has
253 * finished
256 int pthreadpool_signal_fd(struct pthreadpool *pool)
258 return pool->sig_pipe[0];
262 * Do a pthread_join() on all children that have exited, pool->mutex must be
263 * locked
265 static void pthreadpool_join_children(struct pthreadpool *pool)
267 int i;
269 for (i=0; i<pool->num_exited; i++) {
270 int ret;
272 ret = pthread_join(pool->exited[i], NULL);
273 if (ret != 0) {
275 * Severe internal error, we can't do much but
276 * abort here.
278 abort();
281 pool->num_exited = 0;
284 * Deliberately not free and NULL pool->exited. That will be
285 * re-used by realloc later.
290 * Fetch a finished job number from the signal pipe
293 int pthreadpool_finished_jobs(struct pthreadpool *pool, int *jobids,
294 unsigned num_jobids)
296 ssize_t to_read, nread;
298 nread = -1;
299 errno = EINTR;
301 to_read = sizeof(int) * num_jobids;
303 while ((nread == -1) && (errno == EINTR)) {
304 nread = read(pool->sig_pipe[0], jobids, to_read);
306 if (nread == -1) {
307 return -errno;
309 if ((nread % sizeof(int)) != 0) {
310 return -EINVAL;
312 return nread / sizeof(int);
316 * Destroy a thread pool, finishing all threads working for it
319 int pthreadpool_destroy(struct pthreadpool *pool)
321 int ret, ret1;
323 ret = pthread_mutex_lock(&pool->mutex);
324 if (ret != 0) {
325 return ret;
328 if ((pool->num_jobs != 0) || pool->shutdown) {
329 ret = pthread_mutex_unlock(&pool->mutex);
330 assert(ret == 0);
331 return EBUSY;
334 if (pool->num_threads > 0) {
336 * We have active threads, tell them to finish, wait for that.
339 pool->shutdown = 1;
341 if (pool->num_idle > 0) {
343 * Wake the idle threads. They will find
344 * pool->shutdown to be set and exit themselves
346 ret = pthread_cond_broadcast(&pool->condvar);
347 if (ret != 0) {
348 pthread_mutex_unlock(&pool->mutex);
349 return ret;
353 while ((pool->num_threads > 0) || (pool->num_exited > 0)) {
355 if (pool->num_exited > 0) {
356 pthreadpool_join_children(pool);
357 continue;
360 * A thread that shuts down will also signal
361 * pool->condvar
363 ret = pthread_cond_wait(&pool->condvar, &pool->mutex);
364 if (ret != 0) {
365 pthread_mutex_unlock(&pool->mutex);
366 return ret;
371 ret = pthread_mutex_unlock(&pool->mutex);
372 if (ret != 0) {
373 return ret;
375 ret = pthread_mutex_destroy(&pool->mutex);
376 ret1 = pthread_cond_destroy(&pool->condvar);
378 if (ret != 0) {
379 return ret;
381 if (ret1 != 0) {
382 return ret1;
385 ret = pthread_mutex_lock(&pthreadpools_mutex);
386 if (ret != 0) {
387 return ret;
389 DLIST_REMOVE(pthreadpools, pool);
390 ret = pthread_mutex_unlock(&pthreadpools_mutex);
391 assert(ret == 0);
393 close(pool->sig_pipe[0]);
394 pool->sig_pipe[0] = -1;
396 close(pool->sig_pipe[1]);
397 pool->sig_pipe[1] = -1;
399 free(pool->exited);
400 free(pool->jobs);
401 free(pool);
403 return 0;
407 * Prepare for pthread_exit(), pool->mutex must be locked
409 static void pthreadpool_server_exit(struct pthreadpool *pool)
411 pthread_t *exited;
413 pool->num_threads -= 1;
415 exited = (pthread_t *)realloc(
416 pool->exited, sizeof(pthread_t) * (pool->num_exited + 1));
418 if (exited == NULL) {
419 /* lost a thread status */
420 return;
422 pool->exited = exited;
424 pool->exited[pool->num_exited] = pthread_self();
425 pool->num_exited += 1;
428 static bool pthreadpool_get_job(struct pthreadpool *p,
429 struct pthreadpool_job *job)
431 if (p->num_jobs == 0) {
432 return false;
434 *job = p->jobs[p->head];
435 p->head = (p->head+1) % p->jobs_array_len;
436 p->num_jobs -= 1;
437 return true;
440 static bool pthreadpool_put_job(struct pthreadpool *p,
441 int id,
442 void (*fn)(void *private_data),
443 void *private_data)
445 struct pthreadpool_job *job;
447 if (p->num_jobs == p->jobs_array_len) {
448 struct pthreadpool_job *tmp;
449 size_t new_len = p->jobs_array_len * 2;
451 tmp = realloc(
452 p->jobs, sizeof(struct pthreadpool_job) * new_len);
453 if (tmp == NULL) {
454 return false;
456 p->jobs = tmp;
459 * We just doubled the jobs array. The array implements a FIFO
460 * queue with a modulo-based wraparound, so we have to memcpy
461 * the jobs that are logically at the queue end but physically
462 * before the queue head into the reallocated area. The new
463 * space starts at the current jobs_array_len, and we have to
464 * copy everything before the current head job into the new
465 * area.
467 memcpy(&p->jobs[p->jobs_array_len], p->jobs,
468 sizeof(struct pthreadpool_job) * p->head);
470 p->jobs_array_len = new_len;
473 job = &p->jobs[(p->head + p->num_jobs) % p->jobs_array_len];
474 job->id = id;
475 job->fn = fn;
476 job->private_data = private_data;
478 p->num_jobs += 1;
480 return true;
483 static void *pthreadpool_server(void *arg)
485 struct pthreadpool *pool = (struct pthreadpool *)arg;
486 int res;
488 res = pthread_mutex_lock(&pool->mutex);
489 if (res != 0) {
490 return NULL;
493 while (1) {
494 struct timespec ts;
495 struct pthreadpool_job job;
498 * idle-wait at most 1 second. If nothing happens in that
499 * time, exit this thread.
502 clock_gettime(CLOCK_REALTIME, &ts);
503 ts.tv_sec += 1;
505 while ((pool->num_jobs == 0) && (pool->shutdown == 0)) {
507 pool->num_idle += 1;
508 res = pthread_cond_timedwait(
509 &pool->condvar, &pool->mutex, &ts);
510 pool->num_idle -= 1;
512 if (res == ETIMEDOUT) {
514 if (pool->num_jobs == 0) {
516 * we timed out and still no work for
517 * us. Exit.
519 pthreadpool_server_exit(pool);
520 pthread_mutex_unlock(&pool->mutex);
521 return NULL;
524 break;
526 assert(res == 0);
529 if (pthreadpool_get_job(pool, &job)) {
530 ssize_t written;
531 int sig_pipe = pool->sig_pipe[1];
534 * Do the work with the mutex unlocked
537 res = pthread_mutex_unlock(&pool->mutex);
538 assert(res == 0);
540 job.fn(job.private_data);
542 res = pthread_mutex_lock(&pool->mutex);
543 assert(res == 0);
545 written = write(sig_pipe, &job.id, sizeof(job.id));
546 if (written != sizeof(int)) {
547 pthreadpool_server_exit(pool);
548 pthread_mutex_unlock(&pool->mutex);
549 return NULL;
553 if ((pool->num_jobs == 0) && (pool->shutdown != 0)) {
555 * No more work to do and we're asked to shut down, so
556 * exit
558 pthreadpool_server_exit(pool);
560 if (pool->num_threads == 0) {
562 * Ping the main thread waiting for all of us
563 * workers to have quit.
565 pthread_cond_broadcast(&pool->condvar);
568 pthread_mutex_unlock(&pool->mutex);
569 return NULL;
574 int pthreadpool_add_job(struct pthreadpool *pool, int job_id,
575 void (*fn)(void *private_data), void *private_data)
577 pthread_t thread_id;
578 int res;
579 sigset_t mask, omask;
581 res = pthread_mutex_lock(&pool->mutex);
582 if (res != 0) {
583 return res;
586 if (pool->shutdown) {
588 * Protect against the pool being shut down while
589 * trying to add a job
591 res = pthread_mutex_unlock(&pool->mutex);
592 assert(res == 0);
593 return EINVAL;
597 * Just some cleanup under the mutex
599 pthreadpool_join_children(pool);
602 * Add job to the end of the queue
604 if (!pthreadpool_put_job(pool, job_id, fn, private_data)) {
605 pthread_mutex_unlock(&pool->mutex);
606 return ENOMEM;
609 if (pool->num_idle > 0) {
611 * We have idle threads, wake one.
613 res = pthread_cond_signal(&pool->condvar);
614 pthread_mutex_unlock(&pool->mutex);
615 return res;
618 if ((pool->max_threads != 0) &&
619 (pool->num_threads >= pool->max_threads)) {
621 * No more new threads, we just queue the request
623 pthread_mutex_unlock(&pool->mutex);
624 return 0;
628 * Create a new worker thread. It should not receive any signals.
631 sigfillset(&mask);
633 res = pthread_sigmask(SIG_BLOCK, &mask, &omask);
634 if (res != 0) {
635 pthread_mutex_unlock(&pool->mutex);
636 return res;
639 res = pthread_create(&thread_id, NULL, pthreadpool_server,
640 (void *)pool);
641 if (res == 0) {
642 pool->num_threads += 1;
645 assert(pthread_sigmask(SIG_SETMASK, &omask, NULL) == 0);
647 pthread_mutex_unlock(&pool->mutex);
648 return res;