在C++的類中,普通成員函數不能作為pthread_create的線程函數,如果要作為pthread_create中的線程函數,必須是static !
在C語言中,我們使用pthread_create創建線程,線程函數是一個全局函數,所以在C++中,創建線程時,也應該使用一個全局函數。static定義的類的成員函數就是一個全局函數。
更多 參考 http://blog.csdn.net/ksn13/article/details/40538083
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> class Thread { private: pthread_t pid; private: static void * start_thread(void *arg);// //靜態成員函數 public: int start(); virtual void run() = 0; //基類中的虛函數要么實現,要么是純虛函數(絕對不允許聲明不實現,也不純虛) }; int Thread::start() { if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0) //´創建一個線程(必須是全局函數) { return -1; } return 0; } void* Thread::start_thread(void *arg) //靜態成員函數只能訪問靜態變量或靜態函數,通過傳遞this指針進行調用 { Thread *ptr = (Thread *)arg; ptr->run(); //線程的實體是run } class MyThread:public Thread { public: void run(); }; void MyThread::run() { printf("hello world\n"); } int main(int argc,char *argv[]) { MyThread myThread; myThread.start(); //test.run(); sleep(1); return 0; }
編譯運行:
diego@ubuntu:~/myProg/pthreadCpp$ g++ main.cpp -lpthread diego@ubuntu:~/myProg/pthreadCpp$ ./a.out hello world diego@ubuntu:~/myProg/pthreadCpp$