我有一个多线程代码,其复位线程定义为:
bool CTestShellDlg::ResetThreads()
{
//if Main worker thread already finished, Just Reset
if (CheckMainThreadFinished())
{
//reset
}
else
if(KillThreads()) //Go ahead and reset if killing is finished.
{
//reset
}
else
return false; //killing already in progress. gotta wait!
}
KillThreads()定义为:
bool CTestShellDlg::KillThreads()
{
//if killing not already in progress
if (!CheckKillEvent())
{
//Signall the killing event
SetEvent(h_KillEvent);
if (WaitMainThreadFinished())
{
//call some deletes
//Reset the kill event back to non-signalled to indicate it's no longer in progress
ResetEvent(h_KillEvent);
return true; //Killing successful
}
else IERROR
}
else
return false; //Killing already in progress
}
用
bool WaitMainThreadFinished(){WaitForSingleObject(m_hDoIt_Thread, INFINITE);...}
bool CheckMainThreadFinished(){WaitForSingleObject(m_hDoIt_Thread, 0);...}
现在,我可以打电话给KillThreads()。在这个过程中,我WaitForSingleObject(m_hDoIt_Thread,INFINITE)所以我知道它的结尾,它肯定是信号。现在如果我尝试调用ResetThreads(),CheckMainThreadFinished()中的WaitForSingleObject(m_hDoIt_Thread,0)给我WAIT_FAILED,而在我的理解中它应该是WAIT_OBJECT_0。有什么可能导致这种情况? 有趣的是什么如果我连续两次执行ResetThreads()调用,我就不会从CheckMainThreadFinished()获得所述返回值。
答案 0 :(得分:0)
修正了它! 使用了GetLastError(),结果是
的句柄WaitForSingleObject(m_hDoIt_Thread, 0);
无效。原因是默认情况下,MFC线程释放其线程句柄并在线程对象退出时删除它。这会留下一个无效的线程指针和句柄,因此这种检查主句柄是否正常工作的方法将无效,应该使用替代方法。