代码如下:
void CThreadView::OnKillThreads()
{
// tell all threads to shutdown
for (POSITION pos = m_threadList.GetHeadPosition(); pos != NULL; )
{
CGDIThread* pThread = m_threadList.GetNext(pos);
VERIFY(SetEvent(pThread->m_hEventKill));
}
// wait for all threads to finish shutdown
for (int nThreadsLeft = m_threadList.GetCount(); nThreadsLeft != 0; )
{
//×××××××××××××××××××《1》
WaitForSingleObject(CGDIThread::m_hAnotherDead, INFINITE);
Sleep(nThreadsLeft*2);// 200ms for every 100 threads
nThreadsLeft = 0;
for (pos = m_threadList.GetHeadPosition(); pos != NULL; )
{
CGDIThread* pThread = m_threadList.GetNext(pos);
if (WaitForSingleObject(pThread->m_hEventDead, 0) == WAIT_TIMEOUT)
++nThreadsLeft;
}
UpdateTitle(nThreadsLeft);
} // delete all thread objects
while (!m_threadList.IsEmpty())
{
CGDIThread* pThread = m_threadList.RemoveHead();
VERIFY(WaitForSingleObject(pThread->m_hThread, INFINITE) == WAIT_OBJECT_0);
delete pThread;
}
UpdateTitle(); // invalidate the window since all threads are now gone
Invalidate();
}单步跟踪时,为什么会从《1》跳到《2》中,此前,CGDIThread::m_hAnotherDead并没有被操作过的。void CGDIThread::Delete()
{
//×××××××××××××××××××《2》
CWinThread::Delete(); // acknowledge receipt of kill notification
VERIFY(SetEvent(m_hEventDead));
VERIFY(SetEvent(m_hAnotherDead));
}这个例子位于..\samples\VC98\mfc\advanced 目录下的。谢谢解答。
void CThreadView::OnKillThreads()
{
// tell all threads to shutdown
for (POSITION pos = m_threadList.GetHeadPosition(); pos != NULL; )
{
CGDIThread* pThread = m_threadList.GetNext(pos);
VERIFY(SetEvent(pThread->m_hEventKill));
}
// wait for all threads to finish shutdown
for (int nThreadsLeft = m_threadList.GetCount(); nThreadsLeft != 0; )
{
//×××××××××××××××××××《1》
WaitForSingleObject(CGDIThread::m_hAnotherDead, INFINITE);
Sleep(nThreadsLeft*2);// 200ms for every 100 threads
nThreadsLeft = 0;
for (pos = m_threadList.GetHeadPosition(); pos != NULL; )
{
CGDIThread* pThread = m_threadList.GetNext(pos);
if (WaitForSingleObject(pThread->m_hEventDead, 0) == WAIT_TIMEOUT)
++nThreadsLeft;
}
UpdateTitle(nThreadsLeft);
} // delete all thread objects
while (!m_threadList.IsEmpty())
{
CGDIThread* pThread = m_threadList.RemoveHead();
VERIFY(WaitForSingleObject(pThread->m_hThread, INFINITE) == WAIT_OBJECT_0);
delete pThread;
}
UpdateTitle(); // invalidate the window since all threads are now gone
Invalidate();
}单步跟踪时,为什么会从《1》跳到《2》中,此前,CGDIThread::m_hAnotherDead并没有被操作过的。void CGDIThread::Delete()
{
//×××××××××××××××××××《2》
CWinThread::Delete(); // acknowledge receipt of kill notification
VERIFY(SetEvent(m_hEventDead));
VERIFY(SetEvent(m_hAnotherDead));
}这个例子位于..\samples\VC98\mfc\advanced 目录下的。谢谢解答。
又是这个例子!~不知道你是否注意到他的InitInstance()这个虚函数返回的是FALSE,当此函数返回FALSE时,CWinThread类就会调用类成员Delete(),这是MS决定的,你可看看MFC源码!!!建议你对CWinThread的执行流程有个好的理解!!http://www.csdn.net/develop/read_article.asp?id=17341
看来我对MFC的理解太浅了。