#include <process.h>
#include ". hreadmaster.h"
CThreadMaster::CThreadMaster(void)
{
m_ThreadCmd = nothing;
m_hThread = NULL;
m_hEvent = CreateEvent(NULL, FALSE, TRUE, NULL);
m_ThreadId = 0;
m_CycleTime = AlwaysWork;
m_WorkFunction = NULL;
m_lpParameter = NULL;
}
CThreadMaster::~CThreadMaster(void)
{
Stop();
CloseHandle(m_hEvent);
}
void CThreadMaster::Start()
{
if (m_ThreadId!=0)
return;
m_ThreadCmd = nothing;
m_hThread = (HANDLE)_beginthreadex(NULL,0, WorkThread, (void *)this, 0, &m_ThreadId);
}
void CThreadMaster::Stop()
{
if (m_ThreadId==0)
return;
m_ThreadCmd = stop;
WorkNow();
WaitForSingleObject(m_hThread, INFINITE);
m_ThreadCmd = nothing;
m_ThreadId = 0;
m_hThread = NULL;
}
void CThreadMaster::WorkNow()
{
if (m_hThread==0)
{
Start();
SetEvent(m_hEvent);
}else
SetEvent(m_hEvent);
}
unsigned CThreadMaster::WorkThread( void * lpParameter )
{
CThreadMaster * pThis = (CThreadMaster*) lpParameter;
if (pThis==NULL)
return -1;
for(;;)
{
if (pThis->m_CycleTime > AlwaysWork)
WaitForSingleObject(pThis->m_hEvent, pThis->m_CycleTime);
else if (pThis->m_CycleTime<=AlwaysWait)
WaitForSingleObject(pThis->m_hEvent, INFINITE);
if (pThis->m_ThreadCmd==stop)
return 0;
if (pThis->m_WorkFunction!=NULL)
{
try{
(*pThis->m_WorkFunction)(pThis->m_lpParameter);
}catch (...){
}
}
}
return -2;
}
void CThreadMaster::Set(WorkFuncType function, void * parameter, int cycleTime)
{
m_WorkFunction = function;
m_lpParameter = parameter;
m_CycleTime = cycleTime;
}
void CThreadMaster::SetWorkFunction( WorkFuncType function )
{
m_WorkFunction = function;
}
void CThreadMaster::SetWorkParameter( void * parameter)
{
m_lpParameter = parameter;
}
void CThreadMaster::SetCycleTime( int cycleTime )
{
m_CycleTime = cycleTime;
}
unsigned long CThreadMaster::GetThreadId()
{
return m_ThreadId;
}