// UserThread.cpp: implementation of the CUserThread class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "mgrnve.h" #include "UserThread.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CUserThread::CUserThread() { m_hThread = NULL; m_hKill = NULL; m_uThreadState = TS_STOP; } CUserThread::~CUserThread() { StopThread(1); } BOOL CUserThread::StartThread(PTHREAD_FUNC pFunc, PVOID pParam1, PVOID pParam2, PVOID pParam3) { if (m_uThreadState == TS_RUN) { return FALSE; } m_hKill = CreateEvent(NULL, FALSE, FALSE, NULL); if (!m_hKill) { TRACE("CUserThread::StartThread: create kill event failed\n"); return FALSE; } m_ParamSet.pParam1 = this; m_ParamSet.pParam2 = pParam1; m_ParamSet.pParam3 = pParam2; m_ParamSet.pParam4 = pParam3; ULONG uID; m_hThread = chBEGINTHREADEX(NULL, 0, pFunc, &m_ParamSet, 0, &uID); if (!m_hThread) { TRACE("CUserThread::StartThread: create thread failed\n"); return FALSE; } m_uThreadState = TS_RUN; return TRUE; } void CUserThread::StopThread(ULONG uTime) { if (m_uThreadState == TS_STOP) { return; } if (m_hKill && m_hThread) { SetEvent(m_hKill); if (uTime > 0) { ULONG uExitCode; GetExitCodeThread(m_hThread, &uExitCode); if (WaitForSingleObject(m_hThread, uTime) != WAIT_OBJECT_0) { TerminateThread(m_hThread, uExitCode); } }else{ WaitForSingleObject(m_hThread, INFINITE); } } ReleaseHandle(); m_uThreadState = TS_STOP; } void CUserThread::ReleaseHandle() { if (m_uThreadState == TS_STOP) { return; } if (m_hKill && m_hThread) { CloseHandle(m_hThread); m_hThread = NULL; CloseHandle(m_hKill); m_hKill = NULL; } m_uThreadState = TS_STOP; }