线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池可以有效地控制系统中并发线程的数量,避免大量线程之间的切换所带来的性能开销。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
typedef struct {
void (*function)(void *);
void *argument;
} task_t;
typedef struct {
task_t *tasks;
int front;
int rear;
int count;
int capacity;
pthread_mutex_t lock;
pthread_cond_t not_empty;
pthread_cond_t not_full;
} thread_pool_t;
void *worker(void *arg) {
thread_pool_t *pool = (thread_pool_t *)arg;
while (1) {
pthread_mutex_lock(&pool->lock);
while (pool->count == 0) {
pthread_cond_wait(&pool->not_empty, &pool->lock);
}
task_t task = pool->tasks[pool->front++];
pool->front %= pool->capacity;
pool->count--;
pthread_cond_signal(&pool->not_full);
pthread_mutex_unlock(&pool->lock);
task.function(task.argument);
}
return NULL;
}
void thread_pool_init(thread_pool_t *pool, int num_threads, int capacity) {
pool->tasks = (task_t *)malloc(sizeof(task_t) * capacity);
pool->front = pool->rear = pool->count = 0;
pool->capacity = capacity;
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->not_empty, NULL);
pthread_cond_init(&pool->not_full, NULL);
for (int i = 0; i < num_threads; i++) {
pthread_t thread;
pthread_create(&thread, NULL, worker, pool);
pthread_detach(thread);
}
}
void thread_pool_add_task(thread_pool_t *pool, void (*function)(void *), void *argument) {
pthread_mutex_lock(&pool->lock);
while (pool->count == pool->capacity) {
pthread_cond_wait(&pool->not_full, &pool->lock);
}
pool->tasks[pool->rear].function = function;
pool->tasks[pool->rear].argument = argument;
pool->rear = (pool->rear + 1) % pool->capacity;
pool->count++;
pthread_cond_signal(&pool->not_empty);
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_t pool;
thread_pool_init(&pool, 4, 10);
for (int i = 0; i < 10; i++) {
int *num = (int *)malloc(sizeof(int));
*num = i;
thread_pool_add_task(&pool, example_task, num);
}
sleep(5); // Wait for tasks to complete
return 0;
}
通过合理设计和实现线程池,可以有效提升多线程程序的性能和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云