#ifndef PROCESS_THREAD_H
#define PROCESS_THREAD_H
#include "ace/Thread.h"
#include "ace/Thread_Mutex.h"
#include "ace/Synch.h"
#include "IProcess.h"
static ACE_THR_FUNC_RETURN ProcessThreadFunc(void* pVoid);
class ProcessThread
{
public:
ProcessThread();
~ProcessThread();
bool Start();
bool Stop();
void Process(IProcess* pProcess,void* pVoid);
protected:
bool Suspend();
bool Resume();
void Service();
private:
bool m_flag;
bool m_status;
ACE_thread_t m_hThread;
IProcess* m_pProcess;
void* m_pParam;
ACE_Thread_Mutex m_hMutex;
ACE_Condition_Thread_Mutex m_hCond;
friend ACE_THR_FUNC_RETURN ProcessThreadFunc(void* pVoid);
};
#endif
实现
#include "ProcessThread.h"
#include "ThreadPool.h"
ProcessThread::ProcessThread():m_hCond(m_hMutex)
{
m_pProcess=NULL;
}
ProcessThread::~ProcessThread()
{
}
bool ProcessThread::Start()
{
m_flag=true;
Suspend();//启动时候暂停
if(ACE_Thread::spawn(ProcessThreadFunc,this,0,&m_hThread)==-1)return false;
return true;
}
bool ProcessThread::Stop()
{
Resume();
m_flag=false;///放在此处避免重复删除
ACE_Thread::join(m_hThread,NULL,NULL);
return true;
}
bool ProcessThread::Suspend()
{
m_status=false;
return false;
}
bool ProcessThread::Resume()
{
m_status=true;
m_hMutex.acquire();
m_hCond.signal();
m_hMutex.release();
return true;
}
void ProcessThread::Service()
{
while(m_flag)
{
do{
m_hMutex.acquire();
m_hCond.wait();
m_hMutex.release();
}while(!m_status);//如果未设置继续,则一直等待
m_status=false;
if(!m_pProcess){
break; /*** 如果处理的对象为NULL直接退出*/
}
else {
if(m_flag){
m_pProcess->Process(m_pParam);
ThreadPool::Instance()->PutThread(this);
}
}
m_pProcess=NULL;
}
}
void ProcessThread::Process(IProcess* pProcess,void* pVoid)
{
m_pProcess=pProcess;
m_pParam=pVoid;
Resume();
}
ACE_THR_FUNC_RETURN ProcessThreadFunc(void* pVoid)
{
ProcessThread* pProcessThread=(ProcessThread*)pVoid;
pProcessThread->Service();
return 0;
}