在Linux中,可以使用pthread库来创建和管理线程池。下面是一个简单的示例代码:
```c
#include
#include
#include
#define THREAD_POOL_SIZE 5
typedef struct {
void (*task)(void*); // 线程要执行的任务
void* arg; // 任务参数
} task_t;
typedef struct {
pthread_t* threads; // 线程数组
task_t* tasks; // 任务队列
int size; // 线程池大小
int count; // 当前任务数量
int head; // 任务队列的头
int tail; // 任务队列的尾
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t not_empty; // 非空条件变量
pthread_cond_t not_full; // 非满条件变量
} thread_pool_t;
void* thread_func(void* arg) {
thread_pool_t* pool = (thread_pool_t*)arg;
while (1) {
pthread_mutex_lock(&(pool->mutex));
while (pool->count == 0) { // 如果任务队列为空,线程等待非空条件
pthread_cond_wait(&(pool->not_empty), &(pool->mutex));
}
task_t task = pool->tasks[pool->head]; // 取出头部任务
pool->head = (pool->head + 1) % pool->size;
pool->count--;
if (pool->count == pool->size - 1) { // 如果任务队列之前是满的,唤醒非满条件
pthread_cond_broadcast(&(pool->not_full));
}
pthread_mutex_unlock(&(pool->mutex));
// 执行任务
(task.task)(task.arg);
}
return NULL;
}
// 初始化线程池
void thread_pool_init(thread_pool_t* pool, int size) {
pool->threads = (pthread_t*)malloc(size * sizeof(pthread_t));
pool->tasks = (task_t*)malloc(size * sizeof(task_t));
pool->size = size;
pool->count = 0;
pool->head = 0;
pool->tail = 0;
pthread_mutex_init(&(pool->mutex), NULL);
pthread_cond_init(&(pool->not_empty), NULL);
pthread_cond_init(&(pool->not_full), NULL);
int i;
for (i = 0; i < size; i++) {
pthread_create(&(pool->threads[i]), NULL, thread_func, pool);
}
}
// 销毁线程池
void thread_pool_destroy(thread_pool_t* pool) {
int i;
for (i = 0; i < pool->size; i++) {
pthread_cancel(pool->threads[i]);
}
free(pool->threads);
free(pool->tasks);
pthread_mutex_destroy(&(pool->mutex));
pthread_cond_destroy(&(pool->not_empty));
pthread_cond_destroy(&(pool->not_full));
}
// 添加任务到线程池
void thread_pool_add_task(thread_pool_t* pool, void (*task)(void*), void* arg) {
pthread_mutex_lock(&(pool->mutex));
while (pool->count == pool->size) { // 如果任务队列已满,等待非满条件
pthread_cond_wait(&(pool->not_full), &(pool->mutex));
}
pool->tasks[pool->tail].task = task; // 添加任务到尾部
pool->tasks[pool->tail].arg = arg;
pool->tail = (pool->tail + 1) % pool->size;
pool->count++;
if (pool->count == 1) { // 如果任务队列之前是空的,唤醒非空条件
pthread_cond_broadcast(&(pool->not_empty));
}
pthread_mutex_unlock(&(pool->mutex));
}
```
使用示例:
```c
void task_func(void* arg) {
int n = *(int*)arg;
printf("Task %d is running\n", n);
usleep(1000 * n); // 模拟任务执行
}
int main() {
thread_pool_t pool;
thread_pool_init(&pool, THREAD_POOL_SIZE);
int i;
for (i = 0; i < 10; i++) {
// 创建任务参数并添加到线程池
int* arg = (int*)malloc(sizeof(int));
*arg = i;
thread_pool_add_task(&pool, task_func, arg);
}
sleep(10); // 等待所有任务执行完毕
thread_pool_destroy(&pool);
return 0;
}
```
在上面的示例中,我们使用一个简单的任务函数来模拟具体的任务。在主函数中,我们创建了一个线程池,然后添加了10个任务到线程池中,每个任务都带有一个参数。最后,我们使用sleep函数等待所有任务完成,然后销毁线程池。