1. 程式人生 > 其它 >實現執行緒池-Linux C版本

實現執行緒池-Linux C版本

執行緒池的作用

在多執行緒的應用中,執行緒的頻繁建立和銷燬會浪費時間,從而影響效率,所以引進執行緒池和概念,將多個執行緒維護線上程池中,避免了執行緒頻繁建立與銷燬的開銷問題

執行緒池的結構

結構體

struct threadpool_t
{
    pthread_mutex_t lock;         //互斥鎖
    pthread_cond_t notify;        //條件變數:配合互斥鎖來避免死鎖
    pthread_t *threads;           //執行緒陣列
    threadpool_task_t *queue;     //任務佇列
    int thread_count;             //執行緒數
    int queue_size;               //任務數
    int head;                     //頭部元素
    int rail;                     //尾部元素
    int count;                    //等待的任務數
    int shutdown;                 //關閉狀態
    int started;                  //已經啟動的執行緒數
}

函式

//執行緒池建立
threadpool_t *threadpool_create(int thread_count,int queue_size,int flags);
//新增任務
int threadpool_add(threadpool_t *pool, void (*function)(void *),void *argument, int flags);
//執行緒池銷燬
int threadpool_destroy(threadpool_t *pool, int flags);
//執行緒池釋放
int threadpool_free(threadpool_t *pool);
//為執行緒池分配任務
static void *threadpool_thread(void *threadpool);

執行緒池建立

  • 給執行緒池申請空間
  • 初始化成員變數,為執行緒陣列和任務佇列申請空間,初始化鎖
  • 給執行緒陣列建立程序(?)
threadpool_t *threadpool_create(int thread_count,int queue_size,int flags)
{
    threadpool_t *pool;
    do{
        if(thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0|| queue_size > MAX_QUEUE) return NULL;
        if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) break;
        
        pool->thread_count = 0;
        pool->queue_size = queue_size;
        pool->head = pool->tail = pool->count = pool->shutdown = pool->started = 0;
    }
}