views:

473

answers:

2

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?

+7  A: 

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.

Rob Walker
+1  A: 

The m_hThread member of CWinThread is only closed in destruction of the CWinThread object. The object will delete itself if it m_bAutoDelete is set to TRUE. The thread will delete itself after it's worker function or message loop etc finishes, see AfxThreadEntry. The reason the handle is duplicated is to avoid using an invalid handle or accessing an invalid CWinThread if the thread exits and is destroyed before stop() is called.

adzm