线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池可以有效地控制系统中并发线程的数量,避免大量线程之间的切换所带来的性能开销。
以下是一个简单的Linux下C语言实现线程池的示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
typedef struct {
void (*function)(void *);
void *argument;
} thread_pool_task;
typedef struct {
thread_pool_task *tasks;
int task_count;
int task_size;
pthread_mutex_t lock;
pthread_cond_t cond;
} thread_pool;
void *thread_pool_worker(void *arg) {
thread_pool *pool = (thread_pool *)arg;
while (1) {
pthread_mutex_lock(&pool->lock);
while (pool->task_count == 0) {
pthread_cond_wait(&pool->cond, &pool->lock);
}
thread_pool_task task = pool->tasks[--pool->task_count];
pthread_mutex_unlock(&pool->lock);
task.function(task.argument);
}
return NULL;
}
void thread_pool_init(thread_pool *pool, int task_size) {
pool->tasks = malloc(task_size * sizeof(thread_pool_task));
pool->task_count = 0;
pool->task_size = task_size;
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->cond, NULL);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_t thread;
pthread_create(&thread, NULL, thread_pool_worker, pool);
pthread_detach(thread);
}
}
void thread_pool_add_task(thread_pool *pool, void (*function)(void *), void *argument) {
pthread_mutex_lock(&pool->lock);
if (pool->task_count == pool->task_size) {
pool->task_size *= 2;
pool->tasks = realloc(pool->tasks, pool->task_size * sizeof(thread_pool_task));
}
pool->tasks[pool->task_count++] = (thread_pool_task){function, argument};
pthread_cond_signal(&pool->cond);
pthread_mutex_unlock(&pool->lock);
}
void example_task(void *arg) {
int *num = (int *)arg;
printf("Task %d is running\n", *num);
}
int main() {
thread_pool pool;
thread_pool_init(&pool, 10);
for (int i = 0; i < 20; ++i) {
int *arg = malloc(sizeof(int));
*arg = i;
thread_pool_add_task(&pool, example_task, arg);
}
sleep(1); // 等待任务完成
free(pool.tasks);
pthread_mutex_destroy(&pool->lock);
pthread_cond_destroy(&pool->cond);
return 0;
}
通过以上示例和解释,希望你能更好地理解Linux下C语言实现线程池的基础概念、优势、类型、应用场景以及常见问题及解决方法。
领取专属 10元无门槛券
手把手带您无忧上云