Instead of using a boolean to check for the termination event, simply use an event...take a look at the following example:
class CFoo
{
public:
CFoo();
~CFoo();
private:
HANDLE m_hEventForStopThread;
HANDLE m_hEventForWaitThread;
static UINT ThreadFunction(LPVOID* pvParam);
};
CFoo::CFoo()
{
// Create event
HANDLE m_hEventForStopThread = CreateEvent(0, TRUE, FALSE, 0);
HANDLE m_hEventForWaitThread = CreateEvent(0, TRUE, FALSE, 0);
// Start thread
AfxBeginThread(ThreadFunction, this);
}
CFoo::~CFoo()
{
// Trigger thread to stop
::SetEvent(m_hEventForStopThread);
// Wait until thread finished
::WaitForSingleObject(m_hEventForWaitThread, INFINITE);
// Close handles
::CloseHandle(m_hEventForStopThread);
::CloseHandle(m_hEventForWaitThread);
}
UINT CFoo::ThreadFunction(LPVOID* pvParam)
{
CFoo *pParent = static_cast<CFoo *>(pvParam);
while(true)
{
// Check event for stop thread
if(::WaitForSingleObject(pParent->m_hEventStopThread, 0) == WAIT_OBJECT_0)
{
// Set event
::SetEvent(pParent->m_hEventWaitThread);
return 0;
}
// Do your processing
}
}
class CFoo
{
public:
CFoo();
~CFoo();
private:
HANDLE m_hEventForStopThread;
HANDLE m_hEventForWaitThread;
static UINT ThreadFunction(LPVOID* pvParam);
};
CFoo::CFoo()
{
// Create event
HANDLE m_hEventForStopThread = CreateEvent(0, TRUE, FALSE, 0);
HANDLE m_hEventForWaitThread = CreateEvent(0, TRUE, FALSE, 0);
// Start thread
AfxBeginThread(ThreadFunction, this);
}
CFoo::~CFoo()
{
// Trigger thread to stop
::SetEvent(m_hEventForStopThread);
// Wait until thread finished
::WaitForSingleObject(m_hEventForWaitThread, INFINITE);
// Close handles
::CloseHandle(m_hEventForStopThread);
::CloseHandle(m_hEventForWaitThread);
}
UINT CFoo::ThreadFunction(LPVOID* pvParam)
{
CFoo *pParent = static_cast<CFoo *>(pvParam);
while(true)
{
// Check event for stop thread
if(::WaitForSingleObject(pParent->m_hEventStopThread, 0) == WAIT_OBJECT_0)
{
// Set event
::SetEvent(pParent->m_hEventWaitThread);
return 0;
}
// Do your processing
}
}
댓글