先上代码:
class Thread : NoCopy{
Thread():_quit(false), _isRunning(false){}
vartual ~Thread(){}
int start(bool isJoin = false){ //默认是detach模式
if(_isRunning){
return -1;
}
_quit = false;
#ifdef SUPPORT_CPLUSPLUS11
std::thread thd(&Thread::work_thread, this);
if (isJoin) {
thd.join();
} else {
thd.detach();
}
#else
int ret = pthread_create(&_thread_t, NULL, work_thread, (void*)this);
if (ret != 0) {
return -2;
}
if (isJoin) {
void* threadResult = 0;
ret = pthread_join(_thread_t, &threadResult);
if (ret != 0) {
return -3;
}
} else {
ret = pthread_detach(_thread_t);
if (ret != 0) {
return -4;
}
}
#endif
return 0;
}
bool isQuit() const{
_qiut = true;
if(isWaiting){
while(_isRunning){
msleep(10);
}
}
}
bool isRunning() const {
return _isRunning;
}
static void msleep(int ms) {
#ifdef SUPPORT_CPLUSPLUS11
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
#else
usleep(ms * 1000);
#endif
}
protected:
//必须被子类实现
virtual void run() = 0;
private:
#ifdef SUPPORT_CPLUSPLUS11
void work_thread() {
_isRunning = true;
run();
_isRunning = false;
}
#else
static void* work_thread(void* param) {
Thread* pThis = (Thread*)param;
pThis->_isRunning = true;
pThis->run();
pThis->_isRunning = false;
}
#endif
private:
#ifdef SUPPORT_CPLUSPLUS11
std::atomic<bool> _quit;
std::atomic<bool> _isRunning;
#else
volatile bool _quit;
volatile bool _isRunning;
pthread_t _thread_t;
#endif
};
用法示例:
class myThread:public Thread{
public:
myThread(){}
~myThread(){}
protected:
void run(){
while(!isQuit()){
//do something
}
}
};
int main(){
myThread thread;
thread.start();
thread.quit(true);//可以选择是否等待线程结束,默认是等待
}