2013-04-16 23:57:38 -04:00
|
|
|
/* -*- mode: C; c-basic-offset: 4 -*- */
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <errno.h>
|
|
|
|
|
|
|
|
#include "toku_portability.h"
|
|
|
|
#include "toku_pthread.h"
|
|
|
|
#include "toku_assert.h"
|
|
|
|
#include "memory.h"
|
|
|
|
#include "threadpool.h"
|
2013-04-16 23:57:17 -04:00
|
|
|
|
|
|
|
struct threadpool {
|
|
|
|
int max_threads;
|
|
|
|
int current_threads;
|
2013-04-16 23:57:38 -04:00
|
|
|
toku_pthread_t tids[];
|
2013-04-16 23:57:17 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
int threadpool_create(THREADPOOL *threadpoolptr, int max_threads) {
|
2013-04-16 23:57:27 -04:00
|
|
|
size_t size = sizeof (struct threadpool) + max_threads*sizeof (toku_pthread_t);
|
2013-04-16 23:57:33 -04:00
|
|
|
struct threadpool *threadpool = toku_malloc(size);
|
2013-04-16 23:57:17 -04:00
|
|
|
if (threadpool == 0)
|
|
|
|
return ENOMEM;
|
|
|
|
threadpool->max_threads = max_threads;
|
|
|
|
threadpool->current_threads = 0;
|
|
|
|
int i;
|
|
|
|
for (i=0; i<max_threads; i++)
|
2013-04-16 23:57:38 -04:00
|
|
|
threadpool->tids[i] = 0;
|
2013-04-16 23:57:17 -04:00
|
|
|
*threadpoolptr = threadpool;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void threadpool_destroy(THREADPOOL *threadpoolptr) {
|
|
|
|
struct threadpool *threadpool = *threadpoolptr;
|
|
|
|
int i;
|
|
|
|
for (i=0; i<threadpool->current_threads; i++) {
|
|
|
|
int r; void *ret;
|
2013-04-16 23:57:38 -04:00
|
|
|
r = toku_pthread_join(threadpool->tids[i], &ret);
|
2013-04-16 23:57:17 -04:00
|
|
|
assert(r == 0);
|
|
|
|
}
|
|
|
|
*threadpoolptr = 0;
|
2013-04-16 23:57:33 -04:00
|
|
|
toku_free(threadpool);
|
2013-04-16 23:57:17 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void threadpool_maybe_add(THREADPOOL threadpool, void *(*f)(void *), void *arg) {
|
2013-04-16 23:57:35 -04:00
|
|
|
if (threadpool->current_threads < threadpool->max_threads) {
|
2013-04-16 23:57:38 -04:00
|
|
|
int r = toku_pthread_create(&threadpool->tids[threadpool->current_threads], 0, f, arg);
|
2013-04-16 23:57:17 -04:00
|
|
|
if (r == 0) {
|
|
|
|
threadpool->current_threads++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int threadpool_get_current_threads(THREADPOOL threadpool) {
|
|
|
|
return threadpool->current_threads;
|
|
|
|
}
|