如果工作线程完成时间过长,终止工作线程的正确方法是什么?我已经阅读了几篇文章,声称应极其谨慎地使用 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。