在Linux环境下,C语言实现线程池框架可以有效地管理并发任务,提高程序的性能和响应速度。线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。以下是关于Linux C线程池框架的一些基础概念、优势、类型、应用场景以及常见问题及其解决方法。
以下是一个简单的固定大小线程池实现示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_THREADS 5
#define MAX_QUEUE 100
typedef struct {
void (*function)(void *);
void *argument;
} task_t;
typedef struct {
task_t queue[MAX_QUEUE];
int head;
int tail;
int count;
int shutdown;
pthread_mutex_t lock;
pthread_cond_t notify;
} thread_pool_t;
void *thread_pool_worker(void *arg) {
thread_pool_t *pool = (thread_pool_t *)arg;
while (1) {
pthread_mutex_lock(&pool->lock);
while (pool->count == 0 && !pool->shutdown) {
pthread_cond_wait(&pool->notify, &pool->lock);
}
if (pool->shutdown) {
pthread_mutex_unlock(&pool->lock);
pthread_exit(NULL);
}
task_t task = pool->queue[pool->head];
pool->head = (pool->head + 1) % MAX_QUEUE;
pool->count--;
pthread_mutex_unlock(&pool->lock);
task.function(task.argument);
}
}
int thread_pool_init(thread_pool_t *pool, int threads) {
pool->head = 0;
pool->tail = 0;
pool->count = 0;
pool->shutdown = 0;
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->notify, NULL);
for (int i = 0; i < threads; i++) {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_pool_worker, pool) != 0) {
return -1;
}
pthread_detach(thread);
}
return 0;
}
void thread_pool_add_task(thread_pool_t *pool, void (*function)(void *), void *argument) {
pthread_mutex_lock(&pool->lock);
if (pool->count == MAX_QUEUE) {
pthread_mutex_unlock(&pool->lock);
return;
}
pool->queue[pool->tail].function = function;
pool->queue[pool->tail].argument = argument;
pool->tail = (pool->tail + 1) % MAX_QUEUE;
pool->count++;
pthread_cond_signal(&pool->notify);
pthread_mutex_unlock(&pool->lock);
}
void thread_pool_destroy(thread_pool_t *pool) {
pthread_mutex_lock(&pool->lock);
pool->shutdown = 1;
pthread_cond_broadcast(&pool->notify);
pthread_mutex_unlock(&pool->lock);
pthread_mutex_destroy(&pool->lock);
pthread_cond_destroy(&pool->notify);
}
void example_task(void *arg) {
int *num = (int *)arg;
printf("Task %d is running\n", *num);
sleep(1);
}
int main() {
thread_pool_t pool;
thread_pool_init(&pool, MAX_THREADS);
for (int i = 0; i < 10; i++) {
int *num = malloc(sizeof(int));
*num = i;
thread_pool_add_task(&pool, example_task, num);
}
sleep(15);
thread_pool_destroy(&pool);
return 0;
}
这个示例代码实现了一个简单的固定大小线程池,包含线程池初始化、任务添加、线程池销毁等功能。通过这个示例,可以更好地理解线程池的工作原理和实现方法。
领取专属 10元无门槛券
手把手带您无忧上云