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

C/C++ pthread 線程庫封裝:可復用的 Posix 線程池基類

     編輯:關於C++

設計目標

封裝 pthread 創建、同步(互斥鎖)、執行流程,提供基類 Posix,子類重寫 action() 實現具體任務,調用 Run() 啟動線程池。

類結構

// Posix.h
class Posix {
public:
    Posix(); // 默認 8 線程
    int getThreadNumber();
    void setThreadNumber(int n);
    // 互斥鎖封裝
    int pthreadMutexInit();
    int pthreadMutexLock();
    int pthreadMutexUnlock();
    int pthreadMutexDestroy();
    void Run(); // 啟動所有線程
    virtual void action() = 0; // 子類實現
protected:
    int _threadNumber;
    pthread_mutex_t _mutex;
};

關鍵實現:靜態樁函數

pthread_create 第三參數只接受函數指針,不接受成員函數。解決方案:定義 static void* actionRun(void* arg),內部 static_cast(arg)->action()。

// Posix.cpp
static void* actionRun(void* arg) {
    Posix* p = static_cast(arg);
    p->action();
    return NULL;
}

void Posix::Run() {
    pthread_t threads[_threadNumber];
    for (int i = 0; i < _threadNumber; ++i)
        pthread_create(&threads[i], NULL, actionRun, this);
    for (int i = 0; i < _threadNumber; ++i)
        pthread_join(threads[i], NULL);
}

使用示例

// test.h
class Test : public Posix {
    void action() override { cout << pthread_self() << endl; }
};

// main.cpp
int main() {
    Test t; t.setThreadNumber(10); t.Run(); return 0;
}

適用場景

壓力測試工具(HTTP、MySQL 等)、並發任務處理框架。封裝鎖操作便於共享資源同步。

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