Linux下實現簡單的線程池

定義

         什麼是線程池?簡單點說,線程池就是有一堆已經創建好了的線程,初始它們都處於空閒等待狀態,當有新的任務需要處理的時候,就從這個池子裏面取一個空閒等待的線程來處理該任務,當處理完成了就再次把該線程放回池中,以供後面的任務使用。當池子裏的線程全都處理忙碌狀態時,線程池中沒有可用的空閒等待線程,此時,根據需要選擇創建一個新的線程並置入池中,或者通知任務線程池忙,稍後再試。

 

爲什麼要用線程池?

         我們說,線程的創建和銷燬比之進程的創建和銷燬是輕量級的,但是當我們的任務需要大量進行大量線程的創建和銷燬操作時,這個消耗就會變成的相當大。比如,當你設計一個壓力性能測試框架的時候,需要連續產生大量的併發操作,這個是時候,線程池就可以很好的幫上你的忙。線程池的好處就在於線程複用,一個任務處理完成後,當前線程可以直接處理下一個任務,而不是銷燬後再創建,非常適用於連續產生大量併發任務的場合。

 

線程池工作原理

         線程池中每一個線程的工作過程如下:

圖 1: 線程的工作流程

         線程池的任務就在於負責這些線程的創建,銷燬和任務處理參數傳遞、喚醒和等待。

1.      創建若干線程,置入線程池

2.      任務達到時,從線程池取空閒線程

3.      取得了空閒線程,立即進行任務處理

4.      否則新建一個線程,並置入線程池,執行3

5.      如果創建失敗或者線程池已滿,根據設計策略選擇返回錯誤或將任務置入處理隊列,等待處理

6.      銷燬線程池

 

圖 2:線程池的工作原理

 

線程池設計

數據結構設計

任務設計

 

[cpp] view plaincopy

  1. typedef struct tp_work_desc_s TpWorkDesc;  
  2. typedef void (*process_job)(TpWorkDesc*job);  
  3. struct tp_work_desc_s {  
  4.          void *ret; //call in, that is arguments  
  5.          void *arg; //call out, that is return value  
  6. };  


其中,TpWorkDesc是任務參數描述,arg是傳遞給任務的參數,ret則是任務處理完成後的返回值;

 

process_job函數是任務處理函數原型,每個任務處理函數都應該這樣定義,然後將它作爲參數傳給線程池處理,線程池將會選擇一個空閒線程通過調用該函數來進行任務處理;

 

線程設計

 

[cpp] view plaincopy

  1. typedef struct tp_thread_info_s TpThreadInfo;  
  2. struct tp_thread_info_s {  
  3.          pthread_t thread_id; //thread id num  
  4.          TPBOOL is_busy; //thread status:true-busy;flase-idle  
  5.          pthread_cond_t thread_cond;  
  6.          pthread_mutex_t thread_lock;  
  7.          process_job proc_fun;  
  8.          TpWorkDesc* th_job;  
  9.          TpThreadPool* tp_pool;  
  10. };  


TpThreadInfo是對一個線程的描述。

 

thread_id是該線程的ID;

is_busy用於標識該線程是否正處理忙碌狀態;

thread_cond用於任務處理時的喚醒和等待;

thread_lock,用於任務加鎖,用於條件變量等待加鎖;

proc_fun是當前任務的回調函數地址;

th_job是任務的參數信息;

tp_pool是所在線程池的指針;

 

線程池設計

 

[cpp] view plaincopy

  1. typedef struct tp_thread_pool_s TpThreadPool;  
  2. struct tp_thread_pool_s {  
  3.          unsigned min_th_num; //min thread number in the pool  
  4.          unsigned cur_th_num; //current thread number in the pool  
  5.          unsigned max_th_num; //max thread number in the pool  
  6.          pthread_mutex_t tp_lock;  
  7.          pthread_t manage_thread_id; //manage thread id num  
  8.          TpThreadInfo* thread_info;  
  9.          Queue idle_q;  
  10.          TPBOOL stop_flag;  
  11. };  


TpThreadPool是對線程池的描述。

 

min_th_num是線程池中至少存在的線程數,線程池初始化的過程中會創建min_th_num數量的線程;

cur_th_num是線程池當前存在的線程數量;

max_th_num則是線程池最多可以存在的線程數量;

tp_lock用於線程池管理時的互斥;

manage_thread_id是線程池的管理線程ID;

thread_info則是指向線程池數據,這裏使用一個數組來存儲線程池中線程的信息,該數組的大小爲max_th_num;

idle_q是存儲線程池空閒線程指針的隊列,用於從線程池快速取得空閒線程;

stop_flag用於線程池的銷燬,當stop_flag爲FALSE時,表明當前線程池需要銷燬,所有忙碌線程在處理完當前任務後會退出;

算法設計

線程池的創建和初始化

線程創建

創建伊始,線程池線程容量大小上限爲max_th_num,初始容量爲min_th_num;

 

[cpp] view plaincopy

  1. TpThreadPool *tp_create(unsigned min_num, unsigned max_num) {  
  2.     TpThreadPool *pTp;  
  3.     pTp = (TpThreadPool*) malloc(sizeof(TpThreadPool));  
  4.   
  5.     memset(pTp, 0, sizeof(TpThreadPool));  
  6.   
  7.     //init member var  
  8.     pTp->min_th_num = min_num;  
  9.     pTp->cur_th_num = min_num;  
  10.     pTp->max_th_num = max_num;  
  11.     pthread_mutex_init(&pTp->tp_lock, NULL);  
  12.   
  13.     //malloc mem for num thread info struct  
  14.     if (NULL != pTp->thread_info)  
  15.         free(pTp->thread_info);  
  16.     pTp->thread_info = (TpThreadInfo*) malloc(sizeof(TpThreadInfo) * pTp->max_th_num);  
  17.     memset(pTp->thread_info, 0, sizeof(TpThreadInfo) * pTp->max_th_num);  
  18.   
  19.     return pTp;  
  20. }  

 

 

線程初始化

 

[cpp] view plaincopy

  1. TPBOOL tp_init(TpThreadPool *pTp) {  
  2.     int i;  
  3.     int err;  
  4.     TpThreadInfo *pThi;  
  5.   
  6.     initQueue(&pTp->idle_q);  
  7.     pTp->stop_flag = FALSE;  
  8.   
  9.     //create work thread and init work thread info  
  10.     for (i = 0; i < pTp->min_th_num; i++) {  
  11.         pThi = pTp->thread_info +i;  
  12.         pThi->tp_pool = pTp;  
  13.         pThi->is_busy = FALSE;  
  14.         pthread_cond_init(&pThi->thread_cond, NULL);  
  15.         pthread_mutex_init(&pThi->thread_lock, NULL);  
  16.         pThi->proc_fun = def_proc_fun;  
  17.         pThi->th_job = NULL;  
  18.         enQueue(&pTp->idle_q, pThi);  
  19.   
  20.         err = pthread_create(&pThi->thread_id, NULL, tp_work_thread, pThi);  
  21.         if (0 != err) {  
  22.             perror("tp_init: create work thread failed.");  
  23.             clearQueue(&pTp->idle_q);  
  24.             return FALSE;  
  25.         }  
  26.     }  
  27.   
  28.     //create manage thread  
  29.     err = pthread_create(&pTp->manage_thread_id, NULL, tp_manage_thread, pTp);  
  30.     if (0 != err) {  
  31.         clearQueue(&pTp->idle_q);  
  32.         printf("tp_init: creat manage thread failed\n");  
  33.         return FALSE;  
  34.     }  
  35.   
  36.     return TRUE;  
  37. }  

 

 

初始線程池中線程數量爲min_th_num,對這些線程一一進行初始化;

 

將這些初始化的空閒線程一一置入空閒隊列;

創建管理線程,用於監控線程池的狀態,並適當回收多餘的線程資源;

 

線程池的關閉和銷燬

 

[cpp] view plaincopy

  1. void tp_close(TpThreadPool *pTp, TPBOOL wait) {  
  2.     unsigned i;  
  3.   
  4.     pTp->stop_flag = TRUE;  
  5.     if (wait) {  
  6.         for (i = 0; i < pTp->cur_th_num; i++) {  
  7.             pthread_cond_signal(&pTp->thread_info[i].thread_cond);  
  8.         }  
  9.         for (i = 0; i < pTp->cur_th_num; i++) {  
  10.             pthread_join(pTp->thread_info[i].thread_id, NULL);  
  11.             pthread_mutex_destroy(&pTp->thread_info[i].thread_lock);  
  12.             pthread_cond_destroy(&pTp->thread_info[i].thread_cond);  
  13.         }  
  14.     } else {  
  15.         //close work thread  
  16.         for (i = 0; i < pTp->cur_th_num; i++) {  
  17.             kill((pid_t)pTp->thread_info[i].thread_id, SIGKILL);  
  18.             pthread_mutex_destroy(&pTp->thread_info[i].thread_lock);  
  19.             pthread_cond_destroy(&pTp->thread_info[i].thread_cond);  
  20.         }  
  21.     }  
  22.     //close manage thread  
  23.     kill((pid_t)pTp->manage_thread_id, SIGKILL);  
  24.     pthread_mutex_destroy(&pTp->tp_lock);  
  25.   
  26.     //free thread struct  
  27.     free(pTp->thread_info);  
  28.     pTp->thread_info = NULL;  
  29. }  


線程池關閉的過程中,可以選擇是否對正在處理的任務進行等待,如果是,則會喚醒所有任務,然後等待所有任務執行完成,然後返回;如果不是,則將立即殺死所有線程,然後返回,注意:這可能會導致任務的處理中斷而產生錯誤!

 

 

任務處理

 

[cpp] view plaincopy

  1. TPBOOL tp_process_job(TpThreadPool *pTp, process_job proc_fun, TpWorkDesc *job) {  
  2.     TpThreadInfo *pThi ;  
  3.     //fill pTp->thread_info's relative work key  
  4.     pthread_mutex_lock(&pTp->tp_lock);  
  5.     pThi = (TpThreadInfo *) deQueue(&pTp->idle_q);  
  6.     pthread_mutex_unlock(&pTp->tp_lock);  
  7.     if(pThi){  
  8.         pThi->is_busy =TRUE;  
  9.         pThi->proc_fun = proc_fun;  
  10.         pThi->th_job = job;  
  11.         pthread_cond_signal(&pThi->thread_cond);  
  12.         DEBUG("Fetch a thread from pool.\n");  
  13.         return TRUE;  
  14.     }  
  15.     //if all current thread are busy, new thread is created here  
  16.     pthread_mutex_lock(&pTp->tp_lock);  
  17.     pThi = tp_add_thread(pTp);  
  18.     pthread_mutex_unlock(&pTp->tp_lock);  
  19.   
  20.     if(!pThi){  
  21.         DEBUG("The thread pool is full, no more thread available.\n");  
  22.         return FALSE;  
  23.     }  
  24.     DEBUG("No more idle thread, created a new one.\n");  
  25.     pThi->proc_fun = proc_fun;  
  26.     pThi->th_job = job;  
  27.   
  28.     //send cond to work thread  
  29.     pthread_cond_signal(&pThi->thread_cond);  
  30.     return TRUE;  
  31. }  


當一個新任務到達是,線程池首先會檢查是否有可用的空閒線程,如果是,則採用才空閒線程進行任務處理並返回TRUE,如果不是,則嘗試新建一個線程,並使用該線程對任務進行處理,如果失敗則返回FALSE,說明線程池忙碌或者出錯。

 

 

 

[cpp] view plaincopy

  1. static void *tp_work_thread(void *arg) {  
  2.     pthread_t curid;//current thread id  
  3.     TpThreadInfo *pTinfo = (TpThreadInfo *) arg;  
  4.   
  5.     //wait cond for processing real job.  
  6.     while (!(pTinfo->tp_pool->stop_flag)) {  
  7.         pthread_mutex_lock(&pTinfo->thread_lock);  
  8.         pthread_cond_wait(&pTinfo->thread_cond, &pTinfo->thread_lock);  
  9.         pthread_mutex_unlock(&pTinfo->thread_lock);  
  10.   
  11.         //process  
  12.         pTinfo->proc_fun(pTinfo->th_job);  
  13.   
  14.         //thread state be set idle after work  
  15.         //pthread_mutex_lock(&pTinfo->thread_lock);  
  16.         pTinfo->is_busy = FALSE;  
  17.         enQueue(&pTinfo->tp_pool->idle_q, pTinfo);  
  18.         //pthread_mutex_unlock(&pTinfo->thread_lock);  
  19.         DEBUG("Job done, I am idle now.\n");  
  20.     }  
  21. }  


上面這個函數是任務處理函數,該函數將始終處理等待喚醒狀態,直到新任務到達或者線程銷燬時被喚醒,然後調用任務處理回調函數對任務進行處理;當任務處理完成時,則將自己置入空閒隊列中,以供下一個任務處理。

 

 

 

[cpp] view plaincopy

  1. TpThreadInfo *tp_add_thread(TpThreadPool *pTp) {  
  2.     int err;  
  3.     TpThreadInfo *new_thread;  
  4.   
  5.     if (pTp->max_th_num <= pTp->cur_th_num)  
  6.         return NULL;  
  7.   
  8.     //malloc new thread info struct  
  9.     new_thread = pTp->thread_info + pTp->cur_th_num;   
  10.   
  11.     new_thread->tp_pool = pTp;  
  12.     //init new thread's cond & mutex  
  13.     pthread_cond_init(&new_thread->thread_cond, NULL);  
  14.     pthread_mutex_init(&new_thread->thread_lock, NULL);  
  15.   
  16.     //init status is busy, only new process job will call this function  
  17.     new_thread->is_busy = TRUE;  
  18.     err = pthread_create(&new_thread->thread_id, NULL, tp_work_thread, new_thread);  
  19.     if (0 != err) {  
  20.         free(new_thread);  
  21.         return NULL;  
  22.     }  
  23.     //add current thread number in the pool.  
  24.     pTp->cur_th_num++;  
  25.   
  26.     return new_thread;  
  27. }  


上面這個函數用於向線程池中添加新的線程,該函數將會在當線程池沒有空閒線程可用時被調用。

 

 

函數將會新建一個線程,並設置自己的狀態爲busy(立即就要被用於執行任務)。

線程池管理

線程池的管理主要是監控線程池的整體忙碌狀態,當線程池大部分線程處於空閒狀態時,管理線程將適當的銷燬一定數量的空閒線程,以便減少線程池對系統資源的消耗。

 

這裏設計認爲,當空閒線程的數量超過線程池線程數量的1/2時,線程池總體處理空閒狀態,可以適當銷燬部分線程池的線程,以減少線程池對系統資源的開銷。

 

線程池狀態計算

這裏的BUSY_THRESHOLD的值是0.5,也即是當空閒線程數量超過一半時,返回0,說明線程池整體狀態爲閒,否則返回1,說明爲忙。

 

[cpp] view plaincopy

  1. int tp_get_tp_status(TpThreadPool *pTp) {  
  2.     float busy_num = 0.0;  
  3.     int i;  
  4.   
  5.     //get busy thread number  
  6.     busy_num = pTp->cur_th_num - pTp->idle_q.count;     
  7.   
  8.     DEBUG("Current thread pool status, current num: %u, busy num: %u, idle num: %u\n", pTp->cur_th_num, (unsigned)busy_num, pTp->idle_q.count);  
  9.     //0.2? or other num?  
  10.     if (busy_num / (pTp->cur_th_num) < BUSY_THRESHOLD)  
  11.         return 0;//idle status  
  12.     else  
  13.         return 1;//busy or normal status      
  14. }  


線程的銷燬算法

 

 

1.      從空閒隊列中dequeue一個空閒線程指針,該指針指向線程信息數組的某項,例如這裏是p;

2.      銷燬該線程

3.      把線程信息數組的最後一項拷貝至位置p

4.      線程池數量減少一,即cur_th_num--

圖 3:線程銷燬

 

 

[cpp] view plaincopy

  1. TPBOOL tp_delete_thread(TpThreadPool *pTp) {  
  2.     unsigned idx;  
  3.     TpThreadInfo *pThi;  
  4.     TpThreadInfo tT;  
  5.   
  6.     //current thread num can't < min thread num  
  7.     if (pTp->cur_th_num <= pTp->min_th_num)  
  8.         return FALSE;  
  9.     //pthread_mutex_lock(&pTp->tp_lock);  
  10.     pThi = deQueue(&pTp->idle_q);  
  11.     //pthread_mutex_unlock(&pTp->tp_lock);  
  12.     if(!pThi)  
  13.       return FALSE;  
  14.       
  15.     //after deleting idle thread, current thread num -1  
  16.     pTp->cur_th_num--;  
  17.     memcpy(&tT, pThi, sizeof(TpThreadInfo));  
  18.     memcpy(pThi, pTp->thread_info + pTp->cur_th_num, sizeof(TpThreadInfo));  
  19.   
  20.     //kill the idle thread and free info struct  
  21.     kill((pid_t)tT.thread_id, SIGKILL);  
  22.     pthread_mutex_destroy(&tT.thread_lock);  
  23.     pthread_cond_destroy(&tT.thread_cond);  
  24.   
  25.     return TRUE;  
  26. }  


線程池監控

 

 

線程池通過一個管理線程來進行監控,管理線程將會每隔一段時間對線程池的狀態進行計算,根據線程池的狀態適當的銷燬部分線程,減少對系統資源的消耗。

 

[cpp] view plaincopy

  1. static void *tp_manage_thread(void *arg) {  
  2.     TpThreadPool *pTp = (TpThreadPool*) arg;//main thread pool struct instance  
  3.   
  4.     //1?  
  5.     sleep(MANAGE_INTERVAL);  
  6.   
  7.     do {  
  8.         if (tp_get_tp_status(pTp) == 0) {  
  9.             do {  
  10.                 if (!tp_delete_thread(pTp))  
  11.                     break;  
  12.             } while (TRUE);  
  13.         }//end for if  
  14.   
  15.         //1?  
  16.         sleep(MANAGE_INTERVAL);  
  17.     } while (!pTp->stop_flag);  
  18.     return NULL;  
  19. }  

 

 

程序測試

至此,我們的設計需要使用一個測試程序來進行驗證。於是,我們寫下這樣一段代碼。

 

[cpp] view plaincopy

  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. #include "thread_pool.h"  
  4.   
  5. #define THD_NUM 10   
  6. void proc_fun(TpWorkDesc *job){  
  7.     int i;  
  8.     int idx=*(int *)job->arg;  
  9.     printf("Begin: thread %d\n", idx);  
  10.     sleep(3);  
  11.     printf("End:   thread %d\n", idx);  
  12. }  
  13.   
  14. int main(int argc, char **argv){  
  15.     TpThreadPool *pTp= tp_create(5,10);  
  16.     TpWorkDesc pWd[THD_NUM];  
  17.     int i, *idx;  
  18.   
  19.     tp_init(pTp);  
  20.     for(i=0; i < THD_NUM; i++){  
  21.         idx=(int *) malloc(sizeof(int));  
  22.         *idx=i;  
  23.         pWd[i].arg=idx;  
  24.         tp_process_job(pTp, proc_fun, pWd+i);  
  25.         usleep(400000);  
  26.     }  
  27.     //sleep(1);  
  28.     tp_close(pTp, TRUE);  
  29.     free(pTp);  
  30.     printf("All jobs done!\n");  
  31.     return 0;  
  32. }  


執行結果:

 

 

 

源碼下載

地址:https://sourceforge.net/projects/thd-pool-linux/

備註

該線程池設計比較簡單,尚存在不少BUG,歡迎各位提出改進意見。

 

 

修正:

2011/08/04:

tp_close函數增加隊列清空操作,參見源碼註釋部分。

 

[cpp] view plaincopy

  1. void tp_close(TpThreadPool *pTp, TPBOOL wait) {  
  2.     unsigned i;  
  3.   
  4.   
  5.     pTp->stop_flag = TRUE;  
  6.     if (wait) {  
  7.         for (i = 0; i < pTp->cur_th_num; i++) {  
  8.             pthread_cond_signal(&pTp->thread_info[i].thread_cond);  
  9.         }  
  10.         for (i = 0; i < pTp->cur_th_num; i++) {  
  11.             pthread_join(pTp->thread_info[i].thread_id, NULL);  
  12.             pthread_mutex_destroy(&pTp->thread_info[i].thread_lock);  
  13.             pthread_cond_destroy(&pTp->thread_info[i].thread_cond);  
  14.         }  
  15.     } else {  
  16.         //close work thread  
  17.         for (i = 0; i < pTp->cur_th_num; i++) {  
  18.             kill((pid_t)pTp->thread_info[i].thread_id, SIGKILL);  
  19.             pthread_mutex_destroy(&pTp->thread_info[i].thread_lock);  
  20.             pthread_cond_destroy(&pTp->thread_info[i].thread_cond);  
  21.         }  
  22.     }  
  23.     //close manage thread  
  24.     kill((pid_t)pTp->manage_thread_id, SIGKILL);  
  25.     pthread_mutex_destroy(&pTp->tp_lock);  
  26.   
  27.   
  28.     clearQueue(&pTp->idle_q); /** 這裏添加隊列清空 **/  
  29.     //free thread struct  
  30.     free(pTp->thread_info);  
  31.     pTp->thread_info = NULL;  
  32. }  

 

 

上述操作將導致段錯誤,原因是隊列在刪除元素的時候,對元素進行了free。而我們的元素其實是數組中某個元素的地址,這裏將導致段錯誤的發生。源碼中隊列部分增加了元素釋放函數回調,設置該函數爲NULL或者空函數(什麼都不做),在刪除元素時將不會進行free操作。完整源碼請到上面的地址下載。

 

在線程池初始化時,需要設置元素釋放函數爲NULL,參見源碼註釋部分。

 

[cpp] view plaincopy

  1. TPBOOL tp_init(TpThreadPool *pTp) {  
  2.     int i;  
  3.     int err;  
  4.     TpThreadInfo *pThi;  
  5.   
  6.     initQueue(&pTp->idle_q, NULL); /** 初始化時設置元素釋放函數爲NULL **/  
  7.     pTp->stop_flag = FALSE;  
  8.   
  9.     //create work thread and init work thread info  
  10.     for (i = 0; i < pTp->min_th_num; i++) {  
  11.         pThi = pTp->thread_info +i;  
  12.         pThi->tp_pool = pTp;  
  13.         pThi->is_busy = FALSE;  
  14.         pthread_cond_init(&pThi->thread_cond, NULL);  
  15.         pthread_mutex_init(&pThi->thread_lock, NULL);  
  16.         pThi->proc_fun = def_proc_fun;  
  17.         pThi->th_job = NULL;  
  18.         enQueue(&pTp->idle_q, pThi);  
  19.   
  20.         err = pthread_create(&pThi->thread_id, NULL, tp_work_thread, pThi);  
  21.         if (0 != err) {  
  22.             perror("tp_init: create work thread failed.");  
  23.             clearQueue(&pTp->idle_q);  
  24.             return FALSE;  
  25.         }  
  26.     }  
  27.   
  28.     //create manage thread  
  29.     err = pthread_create(&pTp->manage_thread_id, NULL, tp_manage_thread, pTp);  
  30.     if (0 != err) {  
  31.         clearQueue(&pTp->idle_q);  
  32.         printf("tp_init: creat manage thread failed\n");  
  33.         return FALSE;  
  34.     }  
  35.   
  36.     return TRUE;  
  37. }  

 

這裏順便附上隊列頭文件部分源碼:

 

[cpp] view plaincopy

  1. #ifndef __QUEUE_H_  
  2. #define __QUEUE_H_  
  3.   
  4. #include <pthread.h>  
  5.   
  6. typedef struct sNode QNode;  
  7. typedef struct queueLK Queue;  
  8.   
  9. typedef void * EType;  
  10.   
  11. typedef void (*free_data_fun)(void *data);  
  12.   
  13. struct sNode {  
  14.     EType * data;  
  15.     struct sNode *next;  
  16. };  
  17.   
  18. struct queueLK {  
  19.     struct sNode *front;  
  20.     struct sNode *rear;  
  21.     free_data_fun free_fun;  
  22.     unsigned count;  
  23.     pthread_mutex_t lock;  
  24. };  
  25.   
  26. void initQueue(Queue *hq, free_data_fun pff);  
  27. int enQueue(Queue *hq, EType x);  
  28. EType deQueue(Queue *hq);  
  29. EType peekQueue(Queue *hq);  
  30. int isEmptyQueue(Queue *hq);  
  31. void clearQueue(Queue *hq);  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章