自己實現Thread類
-
在C++的類中,普通成員函數不能作為pthread_create的線程函數,如果要作為pthread_create中的線程函數,必須是static !
1 //方式1:使用類的static函數做轉換,配合this指針 2 class Thread 3 { 4 private: 5 pthread_t id; 6 7 static void * start_thread(void *arg) 8 { 9 Thread* thread = (Thread*)arg; 10 thread->run(); 11 } 12 13 public: 14 15 virtual void run() 16 { 17 cout << "success" <<endl; 18 } 19 20 virtual void start() 21 { 22 pthread_create(&id, NULL, start_thread, (void *)this);//傳入this指針是關鍵 23 } 24 }; 25 26 class MyThead: public Thread 27 { 28 public: 29 virtual void run() 30 { 31 cout << "MyThead::run()" << endl; 32 } 33 }; 34 35 36 int main() 37 { 38 MyThead t; 39 t.start(); 40 41 sleep(2); 42 43 return 0; 44 }
1 //方式2:直接使用強制類型轉換,因為this->xxx() 本質上等同於 xxx(this) 2 //方式2比當時1更安全,因為沒有使用static 3 class Thread 4 { 5 private: 6 pthread_t id; 7 8 void* threadFunc(void* arg) 9 { 10 this->run(); 11 } 12 13 public: 14 15 typedef void* (*FUNC)(void*); 16 17 virtual void run() 18 { 19 cout << "success" <<endl; 20 } 21 22 virtual void start() 23 { 24 FUNC callback = (FUNC)&Thread::threadFunc; 25 pthread_create(&id, NULL, callback, this); //此處傳入this是必須的,且在callback中arg不可用,因為為NULL 26 } 27 }; 28 29 class MyThead1: public Thread 30 { 31 public: 32 virtual void run() 33 { 34 sleep(1); 35 cout << "MyThead1::run()" << endl; 36 37 } 38 }; 39 40 class MyThead2: public Thread 41 { 42 public: 43 virtual void run() 44 { 45 cout << "MyThead2::run()" << endl; 46 } 47 }; 48 49 int main() 50 { 51 MyThead1 t1; 52 t1.start(); 53 54 MyThead2 t2; 55 t2.start(); 56 57 sleep(2); 58 59 return 0; 60 }
