Pthread - 线程池(thread pool)实现
线程池简介
线程池在多线程编程中经常要用到,其基本模型仍是生产者/消费者模型,线程池一般由线程池管理器(ThreadPool),工作线程(PoolWorker),任务( Task),任务队列(TaskQueue)四部分组成,其中
线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
这里实现的线程池的任务队列为单向链表,支持的功能有:
添加任务时,线程池中工作线程数可以动态增长到某一阈值
任务执行完毕时,可以动态销毁线程池中的线程
结构体定义说明
任务(Task)结构体定义:
typedef struct task {
TASK_ROUTINE run; // task handler
TASK_PARA_TYPE arg; //para for handler "run"
struct task* next; // pointer to the next task
}task_t;
run为任务接口函数,其参数为arg,next 为指向下一任务的指针。
访问控制结构体定义:
typedef struct condition {
pthread_mutex_t p_mutex; //mutex
pthread_cond_t p_cond; //condition variable
}cond_t;
该结构体封装了 Mutex 和 Condition variable 用于控制任务执行。
线程池(Threadpool)结构体定义
typedef struct threadpool {
cond_t ready; // mutex and condition variable for thread pool
task_t *first; // pointer to the first task in the thread pool
task_t *last; // point to the last past task in the thread pool
int threadcnt; // thread count at the present
int idle; //idle thread count at the present
int max_threads; // max threads for thread pool
int quit; // set 1 when destroying thread pool
}threadpool_t;
该结构体封装了线程池的任务队列头尾指针,工作线程阈值,当前工作线程数目,空闲工作线程数目,以及线程退出标志。
工程文件说明
pool_util.h - 功能函数和宏定义
condition.h,condition.c - Mutex 和 Condition variable 操作封装 >threadpool.h,threadpool.c - 线程池操作封装
makefile - 编译文件
condition.h 定义:
#pragma once
#include <sys/time.h>
#include <pthread.h>
typedef struct condition {
pthread_mutex_t p_mutex; //mutex
pthread_cond_t p_cond; //condition variable
}cond_t;
int cond_init(cond_t* cond); //initial Mutex and Condition variable
int cond_destroy(cond_t* cond); // deallocate Mutex and Condition variable
int cond_lock(cond_t* cond); // acquire Mutex lock
int cond_unlock(cond_t* cond); release Mutex lock
int cond_wait(cond_t* cond); // wait for a condition
int cond_timedwait(cond_t* cond, const struct timespec *tv); // wait for a condition for a specified time
int cond_signal(cond_t* cond); // send signal to a waiting thread
int cond_broadcast(cond_t* cond); // send signal to all waiting thread
pthreadpool.h 定义:
#pragma once
#include "condition.h"
typedef void* (*TASK_ROUTINE) (void*);
typedef void* TASK_PARA_TYPE;
typedef struct task {
TASK_ROUTINE run; // task handler
TASK_PARA_TYPE arg;