본문 바로가기
프로그래밍/Windows API

boolean 변수를 쓰지않고 쓰레드를 종료하는 방법..

by 베리베리 2009. 8. 21.
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
}
}

댓글