在C++的類中,普通成員函數不能作為pthread_create的線程函數,如果要作為pthread_create中的線程函數,必須是static !
在C語言中,我們使用pthread_create創建線程,線程函數是一個全局函數,所以在C++中,創建線程時,也應該使用一個全局函數。static定義的類的成員函數就是一個全局函數。
class Thread { private: pthread_t pid; private: static void * start_thread(void *arg) //靜態成員函數只能訪問靜態變量或靜態函數,通過傳遞this指針進行調用 { Thread *ptr = (Thread *)arg; ptr->fpConnectionRunning(); //線程的實體是run } public: int start() { if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0) //´創建一個線程(必須是全局函數) { return -1; } return 0; } virtual void fpConnectionRunning() = 0; //基類中的虛函數要么實現,要么是純虛函數(絕對不允許聲明不實現,也不純虛) }; class SlamData:public Thread { public: SlamData(){ if(start()==-1){ std::cout<<"pthread_create error ..."<<std::endl; } } ~SlamData(); void fpConnectionRunning(); //實現fpConnectionRunning };