本帖最后由 xieglt 于 2021-5-8 11:04 编辑
CommonThread.H#ifndef H_COMMON_THREAD
#define H_COMMON_THREAD
#include <windows.h> //mfc 下不需要包含此头文件
#include <process.h>
class CCommonThread
{
public:
CCommonThread();
virtual ~CCommonThread();
private:
CCommonThread(const CCommonThread &);
operator = (const CCommonThread &);
protected:
BOOL m_bRun;
HANDLE m_hThread;
HANDLE m_hExit;
private:
static unsigned int WINAPI ThreadFunction(LPVOID lParam);
protected:
BOOL WaitForExit(DWORD dwTime = 50);
void ExitInsideLoop()
{
SetEvent(m_hExit);
}
protected:
virtual unsigned int ThreadBody();
public:
BOOL BeginThread();
void EndThread(UINT nWaitTime = 1000);
};
#endif
CommonThread.CPP#include "stdafx.h"
#include "CommonThread.h"
CCommonThread::CCommonThread()
{
m_bRun = FALSE;
m_hThread = NULL;
m_hExit = NULL;
}
CCommonThread::~CCommonThread()
{
if(m_hExit != NULL)
{
CloseHandle(m_hExit);
m_hExit = NULL;
}
EndThread();
}
BOOL CCommonThread::WaitForExit(DWORD dwTime)
{
DWORD dwRet = WaitForSingleObject(m_hExit,dwTime);
if(dwRet == WAIT_TIMEOUT)
{
return FALSE;
}
else
{
ResetEvent(m_hExit);
return TRUE;
}
}
unsigned int WINAPI CCommonThread::ThreadFunction(LPVOID lParam)
{
unsigned int nRet = 0;
CCommonThread * lpThread = reinterpret_cast<CCommonThread *>(lParam);
nRet = lpThread->ThreadBody();
lpThread->m_bRun = FALSE;
return nRet;
}
unsigned int CCommonThread::ThreadBody()
{
return 0;
}
BOOL CCommonThread::BeginThread()
{
do
{
if(m_bRun)
{
break;
}
if(m_hExit == NULL)
{
m_hExit = ::CreateEvent(NULL,FALSE,FALSE,NULL);
if(m_hExit == NULL)
{
break;
}
}
else
{
ResetEvent(m_hExit);
}
unsigned int dwThreadID = 0;
m_hThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL,0,ThreadFunction,this,0,&dwThreadID));
if(m_hThread == NULL)
{
break;
}
m_bRun = TRUE;
}while(FALSE);
return m_bRun;
}
void CCommonThread::EndThread(UINT nWaitTime)
{
if(m_bRun)
{
SetEvent(m_hExit);
if(WaitForSingleObject(m_hThread,nWaitTime) == WAIT_TIMEOUT)
{
_endthreadex(reinterpret_cast<unsigned int>(m_hThread));
}
CloseHandle(m_hThread);
m_hThread = NULL;
m_bRun = FALSE;
}
}
main.c
#include "stdafx.h"
#include "CommonThread.H"
#include <stdio.h>
class ThreadTest : public CCommonThread
{
public:
ThreadTest(int i=1)
{
_begin = i;
}
private:
unsigned int ThreadBody()
{
for(int i = _begin ; i <= 100 ; i+=2)
{
printf("T%d:%d\t",_begin,i);
if(WaitForExit())
{
break;
}
}
return 0;
}
private:
int _begin;
};
int main(int argc, char* argv[])
{
ThreadTest tt1(1);
ThreadTest tt2(2);
tt1.BeginThread();
tt2.BeginThread();
getchar();
tt1.EndThread();
tt2.EndThread();
return 0;
}
|