15,471
社区成员
发帖
与我相关
我的任务
分享
pWorkThread = AfxBeginThread(..., CREATE_SUSPENDED, ...);
pWorkThread->m_bAutoDelete = FALSE;
pWorkThread->ResumeThread();
WaitForSingleObject(pWorkThread->m_hThread, INFINITE);
delete pWorkThread;
pWorkThread = NULL;
The m_hThread data member is a public variable of type HANDLE. It's only valid if underlying kernel thread object currently exists, and the handle hasn't been closed yet.
The CWinThread destructor calls CloseHandle on m_hThread. If m_bAutoDelete is TRUE when the thread terminates, the CWinThread object is destroyed, which invalidates any pointers to the CWinThread object and its member variables. You may need the m_hThread member to check the thread exit value, or to wait for a signal. To keep the CWinThread object and its m_hThread member during thread execution and after it terminates, set m_bAutoDelete to FALSE before you allow thread execution to continue. Otherwise, the thread may terminate, destroy the CWinThread object, and close the handle before you try to use it. If you use this technique, you are responsible for deletion of the CWinThread object.