I was reading through some threading related code and found this piece of code:
MyThread::start() { //Create a thread m_pThread = AfxBeginThread(/*some parameters*/) //Create a duplicate handle for the created thread m_hDuplicateHandle = DuplicateHandle(/* some more parameters*/) } MyThread::stop() { //Set some variables so that the thread comes out of its run() function WaitForSingleObject(m_hDuplicateHandle, defaultTimeout); CloseHandle(m_hDuplicateHandle); }
My question, why the duplicate handle is required ? Can’t we directly wait on the original thread handle? Does it somehow become invalid?
AfxBeginThread returns a
CWinThread*and MFC assumes it will be managing the handle associated with the thread.So in order to safely use the handle directly you need to duplicate it, otherwise when the thread ends MFC may have closed the handle before you get to the WaitForSingleObject call.
If you were working directly with the win32 CreateThread API then you could certainly wait directly on the returned handle.