#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdbool.h>
#include <unistd.h>
// 任务结构体
typedef struct task {
void (*function)(void *p);
void *arg;
struct task *next;
} task_t;
// 线程池结构体
typedef struct thread_pool {
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_t *threads;
task_t *task_queue;
bool stop;
int thread_count;
} thread_pool_t;
// 线程处理函数
void *thread_function(void *arg) {
thread_pool_t *pool = (thread_pool_t *)arg;
task_t *task;
while (1) {
pthread_mutex_lock(&(pool->lock));
while (pool->task_queue == NULL && !pool->stop) {
pthread_cond_wait(&(pool->cond), &(pool->lock));
}
if (pool->stop) {
pthread_mutex_unlock(&(pool->lock));
pthread_exit(NULL);
}
task = pool->task_queue;
pool->task_queue = task->next;
pthread_mutex_unlock(&(pool->lock));
(*(task->function))(task->arg);
free(task);
}
return NULL;
}
// 初始化线程池
int thread_pool_init(thread_pool_t *pool, int thread_count) {
pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
if (pool->threads == NULL) {
perror("malloc");
return -1;
}
pool->task_queue = NULL;
pool->stop = false;
pool->thread_count = thread_count;
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, thread_function, (void *)pool);
}
return 0;
}
// 添加任务到线程池
int thread_pool_add_task(thread_pool_t *pool, void (*function)(void *), void *arg) {
task_t *new_task = (task_t *)malloc(sizeof(task_t));
if (new_task == NULL) {
perror("malloc");
return -1;
}
new_task->function = function;
new_task->arg = arg;
new_task->next = NULL;
pthread_mutex_lock(&(pool->lock));
task_t *task_iter = pool->task_queue;
if (task_iter == NULL) {
pool->task_queue = new_task;
} else {
while (task_iter->next != NULL) {
task_iter = task_iter->next;
}
task_iter->next = new_task;
}
pthread_cond_signal(&(pool->cond));
pthread_mutex_unlock(&(pool->lock));
return 0;
}
// 销毁线程池
void thread_pool_destroy(thread_pool_t *pool) {
pthread_mutex_lock(&(pool->lock));
pool->stop = true;
pthread_mutex_unlock(&(pool->lock));
pthread_cond_broadcast(&(pool->cond));
for (int i = 0; i < pool->thread_count; ++i) {
pthread_join(pool->threads[i], NULL);
}
free(pool->threads);
task_t *task_iter;
while (pool->task_queue != NULL) {
task_iter = pool->task_queue;
pool->task_queue = task_iter->next;
free(task_iter);
}
pthread_mutex_destroy(&(pool->lock));
pthread_cond_destroy(&(pool->cond));
}
// 示例任务
void sample_task(void *arg) {
int *num = (int *)arg;
printf("Thread %ld processing task %d\n", pthread_self(), *num);
sleep(1);
}
int main() {
thread_pool_t pool;
int thread_count = 4;
thread_pool_init(&pool, thread_count);
int task_count = 10;
int task_nums[task_count];
for (int i = 0; i < task_count; ++i) {
task_nums[i] = i + 1;
thread_pool_add_task(&pool, sample_task, (void *)&task_nums[i]);
}
sleep(5); // 等待线程池处理任务
thread_pool_destroy(&pool);
return 0;
}