#ifndef POSIX_H_ #define POSIX_H_ #include <iostream> #include <pthread.h> #include <unistd.h> #include <stdlib.h> using namespace std; class Posix { public: Posix(); int getThreadNumber(void); //獲取線程數 int pthreadMutexInit(void); //初始化線程鎖,如果不希望使用鎖可以不用,有關鎖的更多,在後面介紹 int pthreadMutexLock(void); //加鎖 int pthreadMutexUnlock(void); //解鎖 int pthreadMutexDestroy(void); //銷毀鎖 void setThreadNumber(int threadNumber); //設置開啟的線程數 void Run(); //所有線程開始執行 virtual void action()=0; //每個線程執行的內容,在子類中重寫 protected: /*線程數*/ int _threadNumber; /*線程鎖*/ pthread_mutex_t _mutex; }; #endif /* POSIX_H_ */
Posix.cpp 因為pthread_create()函數只接收函數指針,不接受C++成員函數,所以另外創建靜態函數actionRun()作為橋接。
#include "Posix.h" Posix::Posix(){ //初始化線程數為8 _threadNumber = 8; } static void* actionRun(void* parm){ Posix* pt = (Posix*)parm; pt->action(); //執行子類重寫的虛函數 return NULL; } /*線程鎖初始化函數*/ int Posix::pthreadMutexInit(void){ return pthread_mutex_init(&this->_mutex,NULL); } /*線程加鎖*/ int Posix::pthreadMutexLock(void){ return pthread_mutex_lock(&this->_mutex); } /*線程解鎖*/ int Posix::pthreadMutexUnlock(void){ return pthread_mutex_unlock(&this->_mutex); } /*銷毀鎖*/ int Posix::pthreadMutexDestroy(void){ return pthread_mutex_destroy(&this->_mutex); } int Posix::getThreadNumber(void){ return this->_threadNumber; } void Posix::setThreadNumber(int threadNumber){ this->_threadNumber = threadNumber; } void Posix::Run(){ pthread_t pthread[this->_threadNumber]; //線程數組 for ( int count = 1 ; count <= this->_threadNumber ; count++ ){ //開始創建線程 //在此,因為pthread_create的第三個參數只接收函數指針,C++成員函數不能進行傳遞,所以創建actionRun為普通的靜態函數,作為橋接,具體實現請往上看actionRun(); if ( pthread_create( &pthread[count] , NULL , actionRun , this) != 0 ){ cerr << "線程創建失敗,線程號 = " << count <<endl; } } for ( int count = 1 ; count <= this->_threadNumber ; count++ ){ if ( pthread_join( pthread[count], NULL ) != 0 ){ cerr << "線程執行失敗,線程號 = " << count << endl; } } // cout << "線程執行完成!" << endl; }
上面是Posix父類的定義與實現,下面我們寫一個新的test類來繼承Posix類 test.h 重寫父類action()函數,把要做的事寫上,這裡我們打印每個線程的ID
#ifndef TEST_H_ #define TEST_H_ #include "Posix.h" class test : public Posix { public: action(){ cout << pthread_self() << endl; //打印線程ID } }
#endif /* TEST_H_ */ 下面是main.cpp
#include "test.h" int main(void){ test* mytest = new test(); mytest->setThreadNumber(10); //設置線程數為10 mytest->Run(); return 0; }