首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言線程池完整實現:基於 pthread 的生產者-消費者模型

     編輯:關於C語言

核心 API 速查

  • 線程創建/退出/等待:pthread_create、pthread_exit、pthread_join
  • 屬性:pthread_attr_init、pthread_attr_setdetachstate
  • 互斥鎖:pthread_mutex_init/lock/unlock/destroy
  • 條件變量:pthread_cond_init/wait/signal/broadcast/destroy

數據結構設計

// 工作節點
typedef struct worker {
    void *(*process)(void *arg);
    void *arg;
    struct worker *next;
} CThread_worker;

// 線程池
typedef struct {
    pthread_mutex_t queue_lock;
    pthread_cond_t queue_ready;
    CThread_worker *queue_head;
    int cur_queue_size;
    int max_thread_num;
    pthread_t *threadid;
    int shutdown;
} CThread_pool;

關鍵流程

初始化 pool_init

  • 分配池結構、初始化鎖與條件變量。
  • 創建固定數量工作線程,執行 thread_routine。

工作線程例程 thread_routine

  1. 加鎖訪問任務隊列。
  2. 隊列為空且未關閉 → pthread_cond_wait 等待(自動釋放鎖,被喚醒後重新加鎖)。
  3. 關閉標志置位 → 解鎖並 pthread_exit。
  4. 取出任務,解鎖,執行任務函數,釋放任務節點。

添加任務 pool_add_worker

  • 創建工作節點,尾插入隊列。
  • 加鎖操作隊列與計數器。
  • 解鎖後 pthread_cond_signal 喚醒一個等待線程。

銷毀線程池 pool_destroy

  • 設置關閉標志,pthread_cond_broadcast 喚醒所有線程。
  • pthread_join 等待所有線程退出。
  • 釋放剩餘任務、鎖、條件變量、池內存。

Java 線程池對比

Java 通過 Executors.newFixedThreadPool/newCachedThreadPool 簡單創建。Tomcat 自定義線程池採用數組存儲空閒線程,按需分批創建(默認 5 個),用完歸還數組。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved