周末看了nginx线程池部分的代码,顺手照抄了一遍,写成了自己的版本。实现上某些地方还是有差异的,不过基本结构全部摘抄。
在这里分享一下。如果你看懂了我的版本,也就证明你看懂了nginx的线程池。
本文只列出了关键数据结构和API,重在理解nginx线程池设计思路。完整代码在最后的链接里。
1.任务节点
typedef void (*CB_FUN)(void *);
//任务结构体
typedef struct task
{
void *argv; //任务函数的参数(任务执行结束前,要保证参数地址有效)
CB_FUN handler; //任务函数(返回值必须为0 非0值用作增加线程,和销毁线程池)
struct task *next; //任务链指针
}zoey_task_t;
handler为函数指针,是实际的任务函数,argv为该函数的参数,next指向下一个任务。
2.任务队列
typedef struct task_queue
{
zoey_task_t *head; //队列头
zoey_task_t **tail; //队列尾
unsigned int maxtasknum; //最大任务限制
unsigned int curtasknum; //当前任务数
}zoey_task_queue_t;
head为任务队列头指针,tail为任务队列尾指针,maxtasknum为队列最大任务数限制,curtasknum为队列当前任务数。
3.线程池
typedef struct threadpool
{
pthread_mutex_t mutex; //互斥锁
pthread_cond_t cond; //条件锁
zoey_task_queue_t tasks;//任务队列
unsigned int threadnum; //线程数
unsigned int thread_stack_size; //线程堆栈大小
}zoey_threadpool_t;
mutex为互斥锁 cond为条件锁。mutex和cond共同保证线程池任务的互斥领取或者添加。
tasks指向任务队列。
threadnum为线程池的线程数
thread_stack_size为线程堆栈大小
4.启动配置
//配置参数
typedef struct threadpool_conf
{
unsigned int threadnum; //线程数
unsigned int thread_stack_size;//线程堆栈大小
unsigned int maxtasknum;//最大任务限制
}zoey_threadpool_conf_t;
启动配置结构体是初始化线程池时的一些参数。
5.初始化线程池
首先检查参数是否合法,然后初始化mutex,cond,key(pthread_key_t)。key用来读写线程全局变量,此全局变量控制线程是否退出。
最后创建线程。
zoey_threadpool_t* zoey_threadpool_init(zoey_threadpool_conf_t *conf)
{
zoey_threadpool_t *pool = NULL;
int error_flag_mutex = 0;
int error_flag_cond = 0;
pthread_attr_t attr;
do{
if (z_conf_check(conf) == -1){ //检查参数是否合法
break;
}
pool = (zoey_threadpool_t *)malloc(sizeof(zoey_threadpool_t));//申请线程池句柄
if (pool == NULL){
break;
}
//初始化线程池基本参数
pool->threadnum = conf->threadnum;
pool->thread_stack_size = conf->thread_stack_size;
pool->tasks.maxtasknum = conf->maxtasknum;
pool->tasks.curtasknum = 0;
z_task_queue_init(&pool->tasks);
if (z_thread_key_create() != 0){//创建一个pthread_key_t,用以访问线程全局变量。
free(pool);
break;
}
if (z_thread_mutex_create(&pool->mutex) != 0){ //初始化互斥锁
z_thread_key_destroy();
free(pool);
break;
}
if (z_thread_cond_create(&pool->cond) != 0){ //初始化条件锁
z_thread_key_destroy();
z_thread_mutex_destroy(&pool->mutex);
free(pool);
break;
}
if (z_threadpool_create(pool) != 0){ //创建线程池
z_thread_key_destroy();
z_thread_mutex_destroy(&pool->mutex);
z_thread_cond_destroy(&pool->cond);
free(pool);
break;
}
return pool;
}while(0);
return NULL;
}








