Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a thread in Win32/MFC

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?

like image 311
Naveen Avatar asked Dec 18 '22 08:12

Naveen


2 Answers

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.

like image 172
Rob Walker Avatar answered Jan 04 '23 07:01

Rob Walker


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.

like image 21
adzm Avatar answered Jan 04 '23 09:01

adzm