在Linux环境下,C语言实现线程池框架是一种高效处理并发请求的方法。线程池通过预先创建一组线程并管理它们,以适应不同任务负载的变化。线程池的核心在于预先创建一定数量的线程,存储在一个线程池中,当有任务到来时,就从这个池子里面取一个空闲等待的线程来处理该任务,当处理完成了就再次把该线程放回池中,以供后面的任务使用。当池子里的线程全都处理忙碌状态时,线程池中没有可用的空闲等待线程,此时,根据需要选择创建一个新的线程并置入池中,或者通知任务线程池忙,稍后再试。
线程池广泛应用于需要处理大量并发请求的场景,如Web服务器、数据库服务器、日志处理等。通过使用线程池,可以显著提高程序的性能和资源利用率。
以下是一个简单的Linux C线程池实现示例,展示了线程池的基础结构和基本操作:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
typedef struct {
void *(*function)(void *);
void *arg;
} threadpool_task_t;
typedef struct {
pthread_t *threads;
threadpool_task_t *tasks;
int task_count;
int max_threads;
int active_threads;
pthread_mutex_t lock;
pthread_cond_t work_cond;
} threadpool_t;
threadpool_t *threadpool_create(int max_threads) {
threadpool_t *pool = malloc(sizeof(threadpool_t));
pool->max_threads = max_threads;
pool->task_count = 0;
pool->active_threads = 0;
pool->threads = malloc(max_threads * sizeof(pthread_t));
pool->tasks = malloc(max_threads * sizeof(threadpool_task_t));
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->work_cond, NULL);
for (int i = 0; i < max_threads; i++) {
pthread_create(&pool->threads[i], NULL, worker, pool);
}
return pool;
}
void *worker(void *arg) {
threadpool_t *pool = (threadpool_t *)arg;
while (1) {
threadpool_task_t task;
pthread_mutex_lock(&pool->lock);
while (pool->task_count == 0) {
pthread_cond_wait(&pool->work_cond, &pool->lock);
}
task = pool->tasks[pool->task_count - 1];
pool->task_count--;
pthread_mutex_unlock(&pool->lock);
task.function(task.arg);
pthread_mutex_lock(&pool->lock);
pool->active_threads--;
if (pool->active_threads == 0) {
pthread_cond_signal(&pool->work_cond);
}
pthread_mutex_unlock(&pool->lock);
}
return NULL;
}
int threadpool_add_task(threadpool_t *pool, void *(*function)(void *), void *arg) {
pthread_mutex_lock(&pool->lock);
if (pool->task_count >= pool->max_threads) {
pthread_mutex_unlock(&pool->lock);
return -1;
}
pool->tasks[pool->task_count].function = function;
pool->tasks[pool->task_count].arg = arg;
pool->task_count++;
pthread_cond_signal(&pool->work_cond);
pthread_mutex_unlock(&pool->lock);
return 0;
}
void threadpool_destroy(threadpool_t *pool) {
for (int i = 0; i < pool->max_threads; i++) {
pthread_join(pool->threads[i], NULL);
}
free(pool->threads);
free(pool->tasks);
pthread_mutex_destroy(&pool->lock);
pthread_cond_destroy(&pool->work_cond);
free(pool);
}
void *print_hello(void *thread_id) {
int thread_id = *((int *)thread_id);
printf("Hello from thread %d\n", thread_id);
pthread_exit(NULL);
}
int main() {
threadpool_t *pool = threadpool_create(5);
for (int i = 0; i < 10; i++) {
int thread_id = i;
threadpool_add_task(pool, print_hello, &thread_id);
}
sleep(1);
threadpool_destroy(pool);
return 0;
}
请注意,这个示例是一个非常基础的实现,仅用于教学目的,实际应用中可能需要考虑更多的错误处理和优化。
领取专属 10元无门槛券
手把手带您无忧上云