技术文摘
C 语言手写线程池
2024-12-31 03:27:20 小编
C 语言手写线程池
在现代编程中,线程池是一种常见且高效的并发编程技术。它可以有效地管理和复用线程资源,提高程序的性能和响应能力。在 C 语言中,我们也可以手写实现一个简单的线程池。
线程池的核心思想是创建一定数量的线程,并将任务放入任务队列中。线程从任务队列中获取任务并执行,完成后再返回等待新的任务。这样可以避免频繁地创建和销毁线程所带来的开销。
我们需要定义线程池的结构体,包括线程数组、任务队列、线程数量、任务队列最大长度等成员变量。
typedef struct {
pthread_t *threads;
void **taskQueue;
int threadCount;
int queueSize;
int front;
int rear;
} ThreadPool;
接下来,实现线程池的初始化函数。在这个函数中,创建指定数量的线程,并初始化任务队列相关的变量。
void initThreadPool(ThreadPool *pool, int threadCount, int queueSize) {
pool->threads = (pthread_t *)malloc(threadCount * sizeof(pthread_t));
pool->taskQueue = (void **)malloc(queueSize * sizeof(void *));
pool->threadCount = threadCount;
pool->queueSize = queueSize;
pool->front = 0;
pool->rear = 0;
for (int i = 0; i < threadCount; i++) {
pthread_create(&pool->threads[i], NULL, threadFunction, pool);
}
}
然后,定义线程执行的函数。在线程函数中,不断从任务队列中获取任务并执行。
void *threadFunction(void *arg) {
ThreadPool *pool = (ThreadPool *)arg;
while (1) {
// 加锁
pthread_mutex_lock(&mutex);
if ((pool->rear + 1) % pool->queueSize == pool->front) {
// 任务队列为满,等待
pthread_cond_wait(&cond, &mutex);
}
void *task = pool->taskQueue[pool->front];
pool->front = (pool->front + 1) % pool->queueSize;
// 解锁
pthread_mutex_unlock(&mutex);
// 执行任务
//...
}
}
还需要实现添加任务到任务队列的函数。
void addTask(ThreadPool *pool, void *task) {
pthread_mutex_lock(&mutex);
if ((pool->rear + 1) % pool->queueSize == pool->front) {
// 任务队列已满,无法添加
printf("Task queue is full!\n");
pthread_mutex_unlock(&mutex);
return;
}
pool->taskQueue[pool->rear] = task;
pool->rear = (pool->rear + 1) % pool->queueSize;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
最后,在程序结束时,需要释放线程池所占用的资源。
通过手写 C 语言线程池,我们可以更好地理解线程池的工作原理和实现机制,为开发高效的并发程序打下坚实的基础。根据实际应用场景的需求,还可以对线程池进行进一步的优化和扩展。