Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux 伺服器

Linux 執行緒池(Thread Pool)原理與 C 語言實作

一、執行緒池是什麼

執行緒池是一種多執行緒的處理形式:先把任務放進佇列,再由预先建立好的執行緒去消化這些任務。池中的執行緒都是背景執行緒,使用預設的堆疊大小與優先級,並處於多執行緒單元中。

當某個執行緒因等待事件而空閒時,執行緒池會補上輔助執行緒,讓所有處理器保持忙碌;若所有執行緒都忙碌且佇列仍有工作,池會在一段時間後再動態增加執行緒,但數量絕不會超過上限,超出的任務只能排隊等待。

執行緒由系統管理,開發者不必煩惱建立與回收的細節,可以把力氣花在真正的業務邏輯上。

使用執行緒池的好處

1. 大幅減少建立與銷毀執行緒所耗費的時間與系統資源。
2. 避免失控地大量建立執行緒,導致記憶體耗盡與「過度切換」。

適合與不適合的場合

適合:單一任務處理時間短、任務數量龐大。
不適合:任務需要特定優先級、任務可能長時間執行而阻塞其他工作、需要把執行緒放進單執行緒單元、需要以識別名稱長期標識並控制某個執行緒(例如個別終止或掛起)。

二、程式實作

main.c

#include <stdio.h>
#include <unistd.h>
#include "thread_pool.h"

/* 功能: 任務處理函數,回傳值: NULL */
void *task_test(void *arg)
{
    printf("\t\tworking on task %d\n", (int)arg);
    sleep(1); /* 休息一秒,延長任務的執行時間 */
    return NULL;
}

int main (int argc, char *argv[])
{
    pool_t pool;
    int i = 0;
    pool_init(&pool, 2);   /* 初始化線程池,兩個工作線程 */
    sleep(1);
    for(i = 0; i < 5; i++){
        sleep(1);
        pool_add_task(&pool, task_test, (void *)i); /* 加入任務 */
    }
    sleep(4);
    pool_uninit(&pool);    /* 銷毀線程池 */
    return 0;
}

thread_pool.h

#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__
#include <pthread.h>

/* 任務回調函數 */
typedef void *(*pool_task_f)(void *arg);

/* 任務句柄 */
typedef struct _task{
    pool_task_f process;   /* 回調函數 */
    void *arg;             /* 回調函數的參數 */
    struct _task *next;
}pool_task;

/* 線程池句柄 */
typedef struct{
    pthread_t *threadid;   /* 線程號 */
    int threads_limit;     /* 允許的活動線程數目 */
    int destroy_flag;      /* 是否銷毀線程池 */
    pool_task *queue_head; /* 等待任務鏈表 */
    int task_in_queue;     /* 當前等待隊列的任務數目 */
    pthread_mutex_t queue_lock; /* 鎖 */
    pthread_cond_t queue_ready; /* 條件變量 */
}pool_t;

void pool_init(pool_t *pool, int threads_limit);
int pool_uninit(pool_t *pool);
int pool_add_task(pool_t *pool, pool_task_f process, void *arg);
#endif

thread_pool.c

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include "thread_pool.h"

static void *pool_thread_server(void *arg);

/* 初始化線程池結構體並創建線程 */
void pool_init(pool_t *pool, int threads_limit)
{
    pool->threads_limit = threads_limit;
    pool->queue_head = NULL;
    pool->task_in_queue = 0;
    pool->destroy_flag = 0;

    pool->threadid = (pthread_t *)calloc(threads_limit, sizeof(pthread_t));
    int i = 0;
    pthread_mutex_init(&(pool->queue_lock), NULL);
    pthread_cond_init(&(pool->queue_ready), NULL);

    for (i = 0; i < threads_limit; i++){
        pthread_create(&(pool->threadid[i]), NULL, pool_thread_server, pool);
    }
    return;
}

/* 銷毀線程池:隊列中未執行的任務不再執行,
   但正在運行的線程會把任務跑完後才退出 */
int pool_uninit(pool_t *pool)
{
    pool_task *head = NULL;
    int i;
    pthread_mutex_lock(&(pool->queue_lock));
    if(pool->destroy_flag)   /* 防止兩次調用 */
        return -1;
    pool->destroy_flag = 1;
    pthread_mutex_unlock(&(pool->queue_lock));

    pthread_cond_broadcast(&(pool->queue_ready)); /* 喚醒所有等待線程 */

    for (i = 0; i < pool->threads_limit; i++)
        pthread_join(pool->threadid[i], NULL); /* 阻塞等待,否則會成僵屍 */
    free(pool->threadid);

    pthread_mutex_lock(&(pool->queue_lock));
    while(pool->queue_head != NULL){
        head = pool->queue_head;
        pool->queue_head = pool->queue_head->next;
        free(head);
    }
    pthread_mutex_unlock(&(pool->queue_lock));

    pthread_mutex_destroy(&(pool->queue_lock));
    pthread_cond_destroy(&(pool->queue_ready));
    return 0;
}

/* 向任務隊列中添加一個任務 */
static void enqueue_task(pool_t *pool, pool_task_f process, void *arg)
{
    pool_task *task = NULL;
    pool_task *member = NULL;
    pthread_mutex_lock(&(pool->queue_lock));
    if(pool->task_in_queue >= pool->threads_limit){
        printf("task_in_queue > threads_limit!\n");
        pthread_mutex_unlock (&(pool->queue_lock));
        return;
    }
    task = (pool_task *)calloc(1, sizeof(pool_task));
    assert(task != NULL);
    task->process = process;
    task->arg = arg;
    task->next = NULL;
    pool->task_in_queue++;
    member = pool->queue_head;
    if(member != NULL){
        while(member->next != NULL)   /* 加入到任務鏈表的最後位置 */
            member = member->next;
        member->next = task;
    }else{
        pool->queue_head = task;     /* 第一個任務,直接指向頭 */
    }
    printf("\t\ttasks %d\n", pool->task_in_queue);
    pthread_cond_signal (&(pool->queue_ready)); /* 喚醒一個等待線程 */
    pthread_mutex_unlock (&(pool->queue_lock));
}

/* 從任務隊列中取出一個任務 */
static pool_task *dequeue_task(pool_t *pool)
{
    pool_task *task = NULL;
    pthread_mutex_lock(&(pool->queue_lock));
    if(pool->destroy_flag){
        pthread_mutex_unlock(&(pool->queue_lock));
        printf("thread 0x%lx will be destroyed\n", pthread_self());
        pthread_exit(NULL);
    }
    if(pool->task_in_queue == 0){
        while((pool->task_in_queue == 0) && (!pool->destroy_flag)){
            printf("thread 0x%lx is leisure\n", pthread_self());
            /* pthread_cond_wait 是原子操作:等待前解鎖,喚醒後加鎖 */
            pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock));
        }
    }else{
        pool->task_in_queue--;
        task = pool->queue_head;
        pool->queue_head = task->next;
        printf("thread 0x%lx received a task\n", pthread_self());
    }
    pthread_mutex_unlock(&(pool->queue_lock));
    return task;
}

/* 對外提供的加入任務介面 */
int pool_add_task(pool_t *pool, pool_task_f process, void *arg)
{
    enqueue_task(pool, process, arg);
    return 0;
}

/* 線程池服務程序 */
static void *pool_thread_server(void *arg)
{
    pool_t *pool = (pool_t *)arg;
    while(1){
        pool_task *task = dequeue_task(pool);
        if(task != NULL){
            printf("thread 0x%lx is busy\n", pthread_self());
            task->process(task->arg);   /* 調用回調函數執行任務 */
            free(task);
            task = NULL;
        }
    }
    pthread_exit(NULL);   /* 這一句應該是不可達的 */
    return NULL;
}

三、重點整理

整個實作的骨架只有三件事:用互斥鎖保護任務鏈表、用條件變量通知空閒線程有活可幹、用 pthread_join 確保銷毀時不會留下僵屍線程。理解這三點,之後要改成動態擴容或加入執行緒命名都不難。編譯時別忘了加上 -lpthread。

Copyright © Linux教程網 All Rights Reserved