小弟在游戏中封装了一个线程类,代码是这样的
类定义如下:
class CThread
{
//状态变量
private:
volatile bool m_state; //运行状态 true 运行 false 停止
private:
pthread_t m_pid; //线程标识
public:
CThread();
virtual ~CThread();
public:
int start();
void stop();
//功能函数
public:
pthread_t GetThreadid();
public:
virtual bool OnEventThreadRun() ;
virtual bool OnEventThreadStart() ;
virtual bool OnEventThreadConclude() ;
//内部函数
private:
static void * ThreadFunction(void* pThreadData);
};
//构造函数
CThread::CThread(){
m_state = false;
m_pid = 0;
}
//析构函数
CThread::~CThread(){};
int CThread::start()
{
if (m_pid != 0) return (int)m_pid;
int errCode = 0;
do{
m_state = true;
pthread_attr_t attributes;
errCode = pthread_attr_init(&attributes);
if (errCode != 0) break;
errCode = pthread_attr_setdetachstate(&attributes,PTHREAD_CREATE_JOINABLE);
if (errCode != 0){
pthread_attr_destroy(&attributes);
break;
}
errCode = pthread_create(&m_pid, &attributes,ThreadFunction,this);
}while(0);
return errCode;
}
void CThread::stop(){
if (m_state ) {
pthread_detach(m_pid);
}
}
pthread_t CThread::GetThreadid()
{
return m_pid;
}
bool CThread::OnEventThreadStart()
{
CCLOG("%s",“run start”);
return true;
}
bool CThread::OnEventThreadRun()
{
CCLOG("%s",“running”);
return true;
}
bool CThread::OnEventThreadConclude()
{
CCLOG("%s",“running end”);
return true;
}
void* CThread::ThreadFunction(void* pThreadData)
{
CCLOG("%s",“sr”);
CThread* thread = (CThread*)pThreadData;
if (thread != NULL){
bool succuess = true;
//线程开始通知
try{
succuess = thread->OnEventThreadStart();
}catch(…){
succuess = false;
}
try {
while(thread->m_state){
timeval timeout = { 10000/1000, 10000%1000};
select(0, NULL, NULL, NULL, &timeout);
thread->OnEventThreadRun();
}
}catch(…){
}
//线程结束通知
try {
thread->OnEventThreadConclude();
}catch(…){
}
}
}
在游戏代码HelloWorldScene.cpp 的 bool HelloWorld::init()中的调用如下
CThread thread;
CCLOG("%d \n",thread.start());
thread.start();
启动线程后,发现程序闪退,但将类定义中的
virtual bool OnEventThreadRun() ;
virtual bool OnEventThreadStart() ;
virtual bool OnEventThreadConclude() ;
修改为
bool OnEventThreadRun() ;
bool OnEventThreadStart() ;
bool OnEventThreadConclude() ;
后程序正常运行,并输出结果。小弟初学,百思不得其解,求大神指点!