周末看了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;}
新聞熱點
疑難解答