封裝 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。
// 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 等)、並發任務處理框架。封裝鎖操作便於共享資源同步。