标签:
写一个线程基类,用户通过继承该基类,重写基类中定义的线程运行函数,即可实现启动线程运行自己的函数。
1 //Thread.h 2 3 #ifndef _THREAD_H 4 #define _THREAD_H 5 6 #include <pthread.h> 7 8 class Thread 9 { 10 public: 11 Thread(); 12 virtual ~Thread(); 13 void Start(); 14 void SetAutoDelete(bool autoDelete) 15 { 16 m_autoDelete = autoDelete; 17 } 18 private: 19 static void *ThreadRoutine(void *arg); 20 virtual void Run() = 0; 21 pthread_t threadId; 22 bool m_autoDelete; 23 }; 24 25 #endif
1 #include "Thread.h" 2 #include <iostream> 3 #include <unistd.h> 4 5 using namespace std; 6 Thread::Thread(): m_autoDelete(false) 7 { 8 cout << "Thread" << endl; 9 } 10 11 Thread::~Thread() 12 { 13 cout << "~Thread" << endl; 14 } 15 16 17 void Thread::Start() 18 { 19 pthread_create(&threadId, NULL, ThreadRoutine, this); //ThreadRoutine必须是static, 20 21 } 22 23 void *Thread::ThreadRoutine(void *arg) 24 { 25 Thread *thread = static_cast<Thread *>(arg); 26 thread->Run(); 27 if (thread->m_autoDelete) 28 delete thread; 29 30 return NULL; 31 }
该类可用于linux系统,用户继承该类,重写Run函数即可。
需要注意几个问题:
1.ThreadRoutine函数必须是static函数。原因是pthread_create函数的第三个参数类型是void *(*fun)(void *),
如果ThreadRoutine不是static,this指针会是它的默认参数,调用pthread_create()时会出错。
2.Start()中,pthread_create()的第四个参数是this指针,用户类继承该线程类,调用Start()时,this指针指向的是用户类,
通过this指向的Run()就是用户自定义的线程函数。
标签:
原文地址:http://www.cnblogs.com/abcdk/p/5657112.html