简体   繁体   English

在 Win32/MFC 中停止线程

[英]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?它会以某种方式变得无效吗?

AfxBeginThread returns a CWinThread* and MFC assumes it will be managing the handle associated with the thread. AfxBeginThread 返回一个CWinThread*并且 MFC 假定它将管理与线程关联的句柄。

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.因此,为了安全地直接使用句柄,您需要复制它,否则当线程结束时 MFC 可能在调用 WaitForSingleObject 之前已经关闭了句柄。

If you were working directly with the win32 CreateThread API then you could certainly wait directly on the returned handle.如果您直接使用 win32 CreateThread API 那么您当然可以直接等待返回的句柄。

The m_hThread member of CWinThread is only closed in destruction of the CWinThread object. CWinThread 的 m_hThread 成员仅在销毁 CWinThread object 时关闭。 The object will delete itself if it m_bAutoDelete is set to TRUE.如果 m_bAutoDelete 设置为 TRUE,object 将自行删除。 The thread will delete itself after it's worker function or message loop etc finishes, see _AfxThreadEntry.该线程将在其工作线程 function 或消息循环等完成后自行删除,请参阅_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.句柄重复的原因是避免使用无效句柄或访问无效的 CWinThread* 如果线程在调用 stop() 之前退出并被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM