萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 線程池 C 實作完整代碼解析 (POSIX pthreads)

線程池避免頻繁建立/銷毀線程開銷,適用於「任務處理時間短、任務數量大」場景。基於 POSIX pthreads 實作完整可編譯代碼。

核心數據結構

typedef void (*pool_task_f)(void *arg);
typedef struct pool_task {
    pool_task_f process;
    void *arg;
    struct pool_task *next;
} pool_task;

typedef struct {
    pthread_t *threadid;
    int threads_limit;
    pool_task *queue_head;
    int task_in_queue;
    int destroy_flag;
    pthread_mutex_t queue_lock;
    pthread_cond_t queue_ready;
} pool_t;

關鍵函式

  • pool_init(pool_t*, int threads):初始化鎖/條件變量、建立固定數量工作線程。
  • pool_add_task(pool_t*, pool_task_f, void*):加鎖 → 入隊 → pthread_cond_signal 喚醒一線程。
  • pool_uninit(pool_t*):置銷毀旗標 → pthread_cond_broadcast 喚醒所有 → pthread_join 回收 → 釋放隊列/鎖/條件變量。
  • pool_thread_server(void*):工作線程主循環,pthread_cond_wait 等待任務 → 執行 → 循環。

main.c 測試程式

void *task_test(void *arg) {
    printf("\t\tworking on task %d\n", (int)arg);
    sleep(1);
    return NULL;
}
int main() {
    pool_t pool;
    pool_init(&pool, 2);          // 2 條工作線程
    sleep(1);
    for (int i=0; i<5; i++) {
        sleep(1);
        pool_add_task(&pool, task_test, (void*)i);  // 投遞 5 個任務
    }
    sleep(4);
    pool_uninit(&pool);
    return 0;
}

編譯與運行

gcc -o thread_pool main.c thread_pool.c -lpthread
./thread_pool

適用/不適用場景

適用不適用
短小任務、大量併發需特定優先級、長時間阻塞任務
無需線程身份標識需單線程單元、需永久標識控制線程

代碼已處理邊界條件 (重複銷毀、隊列清理、鎖/條件變量銷毀),可直接用於生產環境或教學參考。

copyright © 萬盛學電腦網 all rights reserved