在Linux中,使用pthread_t实现线程池需要以下几个步骤:
#include <pthread.h>
#include <stdbool.h>
typedef struct Task {
void (*func)(void *);
void *arg;
struct Task *next;
} Task;
typedef struct ThreadPool {
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_t *threads;
Task *head;
Task *tail;
int thread_count;
int queue_size;
bool shutdown;
} ThreadPool;
ThreadPool *threadpool_init(int thread_count, int queue_size) {
ThreadPool *pool = (ThreadPool *)malloc(sizeof(ThreadPool));
pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
pool->head = NULL;
pool->tail = NULL;
pool->thread_count = thread_count;
pool->queue_size = queue_size;
pool->shutdown = false;
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->cond, NULL);
for (int i = 0; i< thread_count; i++) {
pthread_create(&pool->threads[i], NULL, threadpool_worker, (void *)pool);
}
return pool;
}
void *threadpool_worker(void *arg) {
ThreadPool *pool = (ThreadPool *)arg;
while (1) {
pthread_mutex_lock(&pool->lock);
while (pool->head == NULL && !pool->shutdown) {
pthread_cond_wait(&pool->cond, &pool->lock);
}
if (pool->shutdown) {
pthread_mutex_unlock(&pool->lock);
pthread_exit(NULL);
}
Task *task = pool->head;
pool->head = task->next;
if (pool->head == NULL) {
pool->tail = NULL;
}
pthread_mutex_unlock(&pool->lock);
task->func(task->arg);
free(task);
}
}
void threadpool_add_task(ThreadPool *pool, void (*func)(void *), void *arg) {
Task *task = (Task *)malloc(sizeof(Task));
task->func = func;
task->arg = arg;
task->next = NULL;
pthread_mutex_lock(&pool->lock);
if (pool->tail) {
pool->tail->next = task;
} else {
pool->head = task;
}
pool->tail = task;
pthread_cond_signal(&pool->cond);
pthread_mutex_unlock(&pool->lock);
}
void threadpool_destroy(ThreadPool *pool) {
pthread_mutex_lock(&pool->lock);
pool->shutdown = true;
pthread_cond_broadcast(&pool->cond);
pthread_mutex_unlock(&pool->lock);
for (int i = 0; i< pool->thread_count; i++) {
pthread_join(pool->threads[i], NULL);
}
while (pool->head) {
Task *task = pool->head;
pool->head = task->next;
free(task);
}
pthread_mutex_destroy(&pool->lock);
pthread_cond_destroy(&pool->cond);
free(pool->threads);
free(pool);
}
这样,一个基于pthread_t的线程池就设计和实现完成了。你可以根据自己的需求调整线程池的大小、队列大小等参数。