如果工作线程执行时间过长,正确的终止方式是什么?我读了几篇文章声称TerminateThread应该极度谨慎使用,但我找不到任何可行的替代方法。
伪代码:
void CMyDialog::RunThread()
{
CWinThread* pThread; // pointer to thread
DWORD dwWaitResult; // result of waiting for thread
// start thread
pThread = AfxBeginThread(beginThread, this,
THREAD_PRIORITY_NORMAL,
0,
CREATE_SUSPENDED);
pThread->m_bAutoDelete = FALSE;
pThread->ResumeThread();
// wait for thread to return
dwWaitResult = ::WaitForSingleObject(pThread->m_hThread, (30 * 1000));
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
delete pThread;
// success, continue
break;
case WAIT_TIMEOUT:
// thread taking too long, terminate it
TerminateThread(pThread->m_hThread, 0);
delete pThread;
break;
} // end switch on wait result
}
UINT CMyDialog::beginThread(LPVOID pParam)
{
// convert parameter back to dialog object and call method
CMyDialog* dlg = (CMyDialog*) pParam;
dlg->readDuration();
return 0;
} // end beginThread
void CMyDialog::readDuration()
{
// call a dll function that may take longer than we are prepared to wait,
// or even hang
} // end readDuration
这样可以吗?欢迎收到所有的评论和建议。
我正在使用Visual Studio 2008中的MFC/C++。在Vista上开发,针对XP、Vista和7进行开发。