Linux下c++使用pthread库
pthread 库是纯c库,没有类指针的概念,当想phread_create中传递类成员函数时,就会报错,这里针对这种情况,对线程创建做了必要封装,较为简单,继承类,实现run接口,然后使用start启动线程即可,有点像Qt中线程的用法
/* * ThreadBase.h * * Created on: Oct 25, 2016 * Author: tla001 */ #ifndef THREADBASE_H_ #define THREADBASE_H_ extern "C"{ #include <pthread.h> #include <stdio.h> } class ThreadBase { public: ThreadBase(); virtual ~ThreadBase(); int start(); int stop();//只有stopFlag内嵌如run()才有效 int isStop(); int isStart(); int join(); virtual void run()=0; private: static void *thread_proxy_func(void *args); int stopFlag;//1停止 int startFlag;//1开始 pthread_t tid; }; #endif /* THREADBASE_H_ */
/* * ThreadBase.cpp * * Created on: Oct 25, 2016 * Author: tla001 */ #include "ThreadBase.h" ThreadBase::ThreadBase() { // TODO Auto-generated constructor stub tid=-1; stopFlag=0; startFlag=0; } ThreadBase::~ThreadBase() { // TODO Auto-generated destructor stub } int ThreadBase::start(){ int ret=pthread_create(&tid,NULL,thread_proxy_func,this); if(ret==0){ startFlag=1; // printf("startFlag= %d\n",startFlag); } return ret; } int ThreadBase::stop(){ stopFlag=1; return pthread_join(tid,NULL); } int ThreadBase::join(){ return pthread_join(tid,NULL); } int ThreadBase::isStop(){ return stopFlag; } int ThreadBase::isStart(){ return startFlag; } void *ThreadBase::thread_proxy_func(void *args){ ThreadBase *pThread=static_cast<ThreadBase*>(args); // printf("thread run\n"); pThread->run(); if(pThread->stopFlag==1) delete pThread; return NULL; }
转载请注明出处:http://www.cnblogs.com/tla001/
一起学习,一起进步