#ifndef _ZKit_ThreadBase_h_
#define _ZKit_ThreadBase_h_
#include "AX_Thread.h"
#include "ZKit_Config.h"
BEGIN_ZKIT
class ThreadBase
{
public:
ThreadBase(int nStackSize = 0);
virtual ~ThreadBase(void);
virtual bool start(void);
virtual bool stop(void);
virtual bool terminate(int signal); //最好用stop正常退出线程,除非是事先知道必须强制退出
public:
AX_hthread_t getThreadHandle(void) const { return _handle; }
AX_thread_t getThreadId(void) const { return _threadId; }
bool isRunning(void) const { return _running; }
bool isTerminated(void) const { return _terminating; }
protected:
void threadStopped(void);
//线程执行函数,返回值<0就退出线程
virtual int run(void) = 0;
private:
ThreadBase(const ThreadBase &);
ThreadBase & operator=(const ThreadBase &) { return *this; }
static void * threadFunc(void * arg);
protected:
int _stackSize;
bool _running;
bool _terminating;
AX_hthread_t _handle;
AX_thread_t _threadId;
};
END_ZKIT
#endif // _ZKit_ThreadBase_h_
////////////////////////////////////////////////////////
#include "ZKit_ThreadBase.h"
BEGIN_ZKIT
void* ThreadBase::threadFunc(void *arg)
{
ThreadBase *thread = (ThreadBase *)arg;
if (thread == 0)
{
return 0; // error.
}
while (!thread->isTerminated())
{
if (thread->run() < 0)
{
printf("\nthread=%d exit because of return value!", thread->getThreadId());
break;
}
}
thread->threadStopped();
printf("\nthread exit: %d", thread->getThreadId());
return 0;
}
ThreadBase::ThreadBase(int nStackSize /* = 0 */)
:_stackSize(nStackSize)
{
_handle = 0;
_running = false;
_terminating = true;
}
ThreadBase::~ThreadBase()
{
stop();
}
bool ThreadBase::start()
{
if (!_terminating||_running)
return true;
_terminating = false;
_running = true;
int ret = AX_Thread::spawn(threadFunc, this, THR_NEW_LWP | THR_JOINABLE,
&_threadId, &_handle, AX_DEFAULT_THREAD_PRIORITY, 0, _stackSize);
if ( ret < 0 )
{
_terminating = true;
_running = false;
return false;
}
return true;
}
bool ThreadBase::stop()
{
if ( isRunning() )
{
_terminating = true;
AX_thr_func_return ret = 0;
AX_Thread::join(_handle, &ret);
}
return true;
}
bool ThreadBase::terminate(int signal)
{
if ( isRunning() )
{
AX_Thread::kill(_handle, signal);
threadStopped();
}
return true;
}
void ThreadBase::threadStopped(void)
{
_terminating = true;
_running = false;
_handle = 0;
}
END_ZKIT
原文链接: https://www.cnblogs.com/joeguo/archive/2010/09/03/1889238.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/14649
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!