Stop flow in Win32 / MFC

I read through some code related to threads 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 is why duplicate descriptor is required? Can't we wait right on the handle of the source stream? Is this somehow invalid?

+3
source share
2 answers

AfxBeginThread returns CWinThread*, and MFC assumes that it will handle the handle associated with the thread.

So, in order to use the descriptor safely, you need to duplicate it, otherwise, when the end of the MFC stream can close the descriptor before you go to the WaitForSingleObject call.

API- win32 CreateThread, .

+8

m_hThread CWinThread CWinThread. , m_bAutoDelete TRUE. , .., . _AfxThreadEntry. , , , CWinThread *, stop().

+2

Source: https://habr.com/ru/post/1705043/


All Articles