什么是線程池:
首先,顧名思義,就是把一堆開辟好的線程放在一個池子里統一管理,就是一個線程池。
其次,為什么要用線程池,難道來一個請求給它申請一個線程,請求處理完了釋放線程不行么?也行,但是如果創建線程和銷毀線程的時間比線程處理請求的時間長,而且請求很多的情況下,我們的CPU資源都浪費在了創建和銷毀線程上了,所以這種方法的效率比較低,於是,我們可以將若干已經創建完成的線程放在一起統一管理,如果來了一個請求,我們從線程池中取出一個線程來處理,處理完了放回池內等待下一個任務,線程池的好處是避免了繁瑣的創建和結束線程的時間,有效的利用了CPU資源。
按照我的理解,線程池的作用和雙緩沖的作用類似,可以完成任務處理的“魚貫”動作。
最后,如何才能創建一個線程池的模型呢,一般需要以下三個參與者:
1、線程池結構,它負責管理多個線程並提供任務隊列的接口
2、工作線程,它們負責處理任務
3、任務隊列,存放待處理的任務
有了三個參與者,下一個問題就是怎么使線程池安全有序的工作,可以使用POSIX中的信號量、互斥鎖和條件變量等同步手段。有了這些認識,我們就可以創建自己的線程池
代碼示例如下:
#include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <assert.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <errno.h> #include "threadpool.h" #define DEFAULT_TIME 10 /*10s檢測一次*/ #define MIN_WAIT_TASK_NUM 10 /*如果queue_size > MIN_WAIT_TASK_NUM 添加新的線程到線程池*/ #define DEFAULT_THREAD_VARY 10 /*每次創建和銷毀線程的個數*/ #define true 1 #define false 0 typedef struct { void *(*function)(void *); /*函數指針,回調函數*/ void *arg; /*上面函數的參數*/ } threadpool_task_t; /*任務結構體*/ struct threadpool_t { pthread_mutex_t lock; /*用於鎖住當前這個結構體體taskpoll*/ pthread_mutex_t thread_counter; /*記錄忙狀態線程個數*/ pthread_cond_t queue_not_full; /*當任務隊列滿時,添加任 務的線程阻塞,等待此條件變量*/ pthread_cond_t queue_not_empty; /*任務隊列里不為空時,通知等待任務的線程*/ pthread_t *threads; /*保存工作線程tid的數組*/ pthread_t adjust_tid; /*管理線程tid*/ threadpool_task_t *task_queue; /*任務隊列*/ int min_thr_num; /*線程組內默認最小線程數*/ int max_thr_num; /*線程組內默認最大線程數*/ int live_thr_num; /*當前存活線程個數*/ int busy_thr_num; /*忙狀態線程個數*/ int wait_exit_thr_num; /*要銷毀的線程個數*/ int queue_front; /*隊頭索引下標*/ int queue_rear; /*隊未索引下標*/ int queue_size; /*隊中元素個數*/ int queue_max_size; /*隊列中最大容納個數*/ int shutdown; /*線程池使用狀態,true或false*/ }; /** * @function void *threadpool_thread(void *threadpool) * @desc the worker thread * @param threadpool the pool which own the thread */ void *threadpool_thread(void *threadpool); /** * @function void *adjust_thread(void *threadpool); * @desc manager thread * @param threadpool the threadpool */ void *adjust_thread(void *threadpool); /** * check a thread is alive */ int is_thread_alive(pthread_t tid); int threadpool_free(threadpool_t *pool); threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size) { int i; threadpool_t *pool = NULL; do{ if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) { printf("malloc threadpool fail"); break; /*跳出do while*/ } pool->min_thr_num = min_thr_num; pool->max_thr_num = max_thr_num; pool->busy_thr_num = 0; pool->live_thr_num = min_thr_num; pool->queue_size = 0; pool->queue_max_size = queue_max_size; pool->queue_front = 0; pool->queue_rear = 0; pool->shutdown = false; pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num); if (pool->threads == NULL) { printf("malloc threads fail"); break; } memset(pool->threads, 0, sizeof(pool->threads)); pool->task_queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size); if (pool->task_queue == NULL) { printf("malloc task_queue fail"); break; } if (pthread_mutex_init(&(pool->lock), NULL) != 0 || pthread_mutex_init(&(pool->thread_counter), NULL) != 0 || pthread_cond_init(&(pool->queue_not_empty), NULL) != 0 || pthread_cond_init(&(pool->queue_not_full), NULL) != 0) { printf("init the lock or cond fail"); break; } /* 啟動min_thr_num個work thread */ for (i = 0; i < min_thr_num; i++) { pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool); printf("start thread 0x%x...\n", (unsigned int)pool->threads[i]); } pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void *)pool); return pool; }while(0); threadpool_free(pool); /*前面代碼調用失敗時,釋放poll存儲空間*/ return NULL; } int threadpool_add(threadpool_t *pool, void*(*function)(void *arg), void *arg) { pthread_mutex_lock(&(pool->lock)); while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown)) { pthread_cond_wait(&(pool->queue_not_full), &(pool->lock)); } if (pool->shutdown) { pthread_mutex_unlock(&(pool->lock)); } /*添加任務到任務隊列里*/ if (pool->task_queue[pool->queue_rear].arg != NULL) { free(pool->task_queue[pool->queue_rear].arg); pool->task_queue[pool->queue_rear].arg = NULL; } pool->task_queue[pool->queue_rear].function = function; pool->task_queue[pool->queue_rear].arg = arg; pool->queue_rear = (pool->queue_rear + 1)%pool->queue_max_size; pool->queue_size++; /*任務隊列不為空,喚醒等待處理任務的線程*/ pthread_cond_signal(&(pool->queue_not_empty)); pthread_mutex_unlock(&(pool->lock)); return 0; } void *threadpool_thread(void *threadpool) { threadpool_t *pool = (threadpool_t *)threadpool; threadpool_task_t task; while(true) { /* Lock must be taken to wait on conditional variable */ /*剛創建出線程,等待任務隊列里有任務,否則阻塞等待任務隊列里有任務后再喚醒接收任務*/ pthread_mutex_lock(&(pool->lock)); while ((pool->queue_size == 0) && (!pool->shutdown)) { printf("thread 0x%x is waiting\n", (unsigned int)pthread_self()); pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock)); /*清除指定數目的空閑線程,如果要結束的線程個數大於0,結束線程*/ if (pool->wait_exit_thr_num > 0) { pool->wait_exit_thr_num--; /*如果線程池里線程個數大於最小值時可以結束當前線程*/ if (pool->live_thr_num > pool->min_thr_num) { printf("thread 0x%x is exiting\n", (unsigned int)pthread_self()); pool->live_thr_num--; pthread_mutex_unlock(&(pool->lock)); pthread_exit(NULL); } } } /*如果指定了true,要關閉線程池里的每個線程,自行退出處理*/ if (pool->shutdown) { pthread_mutex_unlock(&(pool->lock)); printf("thread 0x%x is exiting\n", (unsigned int)pthread_self()); pthread_exit(NULL); } /*從任務隊列里獲得任務*/ task.function = pool->task_queue[pool->queue_front].function; task.arg = pool->task_queue[pool->queue_front].arg; pool->queue_front = (pool->queue_front + 1)%pool->queue_max_size; pool->queue_size--; /*通知可以有新的任務添加進來*/ pthread_cond_broadcast(&(pool->queue_not_full)); pthread_mutex_unlock(&(pool->lock)); /*執行任務*/ printf("thread 0x%x start working\n", (unsigned int)pthread_self()); pthread_mutex_lock(&(pool->thread_counter)); pool->busy_thr_num++; /*忙狀態線程數加1*/ pthread_mutex_unlock(&(pool->thread_counter)); (*(task.function))(task.arg); /*執行回調函數任務*/ //task.function(task.arg); /*執行回調函數任務*/ /*任務結束處理*/ printf("thread 0x%x end working\n", (unsigned int)pthread_self()); pthread_mutex_lock(&(pool->thread_counter)); pool->busy_thr_num--; /*忙狀態數減1*/ pthread_mutex_unlock(&(pool->thread_counter)); } pthread_exit(NULL); //return (NULL); } void *adjust_thread(void *threadpool) { int i; threadpool_t *pool = (threadpool_t *)threadpool; while (!pool->shutdown) { sleep(DEFAULT_TIME); /*延時10秒*/ pthread_mutex_lock(&(pool->lock)); int queue_size = pool->queue_size; int live_thr_num = pool->live_thr_num; pthread_mutex_unlock(&(pool->lock)); pthread_mutex_lock(&(pool->thread_counter)); int busy_thr_num = pool->busy_thr_num; pthread_mutex_unlock(&(pool->thread_counter)); /*任務數大於最小線程池個數並且存活的線程數少於最大線程個數時,創建新線程*/ if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num) { pthread_mutex_lock(&(pool->lock)); int add = 0; /*一次增加DEFAULT_THREAD個線程*/ for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY && pool->live_thr_num < pool->max_thr_num; i++) { if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) { pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool); add++; pool->live_thr_num++; } } pthread_mutex_unlock(&(pool->lock)); } /*銷毀多余的空閑線程*/ if ((busy_thr_num * 2) < live_thr_num && live_thr_num > pool->min_thr_num) { /*一次銷毀DEFAULT_THREAD個線程*/ pthread_mutex_lock(&(pool->lock)); pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; pthread_mutex_unlock(&(pool->lock)); for (i = 0; i < DEFAULT_THREAD_VARY; i++) { /*通知處在空閑狀態的線程*/ pthread_cond_signal(&(pool->queue_not_empty)); } } } } int threadpool_destroy(threadpool_t *pool) { int i; if (pool == NULL) { return -1; } pool->shutdown = true; /*先銷毀管理線程*/ pthread_join(pool->adjust_tid, NULL); for (i = 0; i < pool->live_thr_num; i++) { /*通知所有的空閑線程*/ pthread_cond_broadcast(&(pool->queue_not_empty)); pthread_join(pool->threads[i], NULL); } threadpool_free(pool); return 0; } int threadpool_free(threadpool_t *pool) { if (pool == NULL) { return -1; } if (pool->task_queue) { free(pool->task_queue); } if (pool->threads) { free(pool->threads); pthread_mutex_lock(&(pool->lock)); pthread_mutex_destroy(&(pool->lock)); pthread_mutex_lock(&(pool->thread_counter)); pthread_mutex_destroy(&(pool->thread_counter)); pthread_cond_destroy(&(pool->queue_not_empty)); pthread_cond_destroy(&(pool->queue_not_full)); } free(pool); pool = NULL; return 0; } int threadpool_all_threadnum(threadpool_t *pool) { int all_threadnum = -1; pthread_mutex_lock(&(pool->lock)); all_threadnum = pool->live_thr_num; pthread_mutex_unlock(&(pool->lock)); return all_threadnum; } int threadpool_busy_threadnum(threadpool_t *pool) { int busy_threadnum = -1; pthread_mutex_lock(&(pool->thread_counter)); busy_threadnum = pool->busy_thr_num; pthread_mutex_unlock(&(pool->thread_counter)); return busy_threadnum; } int is_thread_alive(pthread_t tid) { int kill_rc = pthread_kill(tid, 0); if (kill_rc == ESRCH) { return false; } return true; } /*測試使用,作成庫時請注釋掉下面代碼*/ #if 1 void *process(void *arg) { printf("thread 0x%x working on task %d\n ",(unsigned int)pthread_self(),*(int *)arg); sleep(1); printf("task %d is end\n",*(int *)arg); return NULL; } int main(void) { threadpool_t *thp = threadpool_create(3,100,100); /*線程池里最小3個線程,最大100個,隊列最大值12*/ printf("pool inited"); int *num = (int *)malloc(sizeof(int)*20); //int num[20]; int i; for (i=0;i<10;i++) { num[i]=i; printf("add task %d\n",i); threadpool_add(thp,process,(void*)&num[i]); } sleep(10); threadpool_destroy(thp); } #endif