自己实现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 }