简体   繁体   English

如何在MFC中停止主线程和等待子线程

[英]How can I stop main thread and waiting sub thread in MFC

I am using ::WaitForSingleObject(event, INFINITE) in main thread, and in sub thread I use ::SetEvent(event) when finish sub thread. 我在主线程中使用::WaitForSingleObject(event, INFINITE) ,在子线程中,当完成子线程时,我使用::SetEvent(event) But it does not work. 但这行不通。 I wonder why?? 我想知道为什么??

One Standard way for waiting a thread exit, is to use WaitForSingleObject with the handle of the thread, and doing so reliability involves using _beginthreadex for creating the thread. 等待线程退出的一种标准方法是将WaitForSingleObject与线程的句柄一起使用,而这样做的可靠性包括使用_beginthreadex创建线程。

HANDLE hThread = reinterpret_cast<HANDLE>( _beginthreadex( ... ) );
if ( hThread ) {
   DWORD dwRet = WaitForSingleObject( hThread, INIFINITE );
   if ( dwRet == WAIT_OBJECT_0 ) {
      // OK
   } else {
      // Error
   }
   CloseHandle( hThread );
} else {
   // Error
}

The handle of a thread created with AfxBeginThread may be obtained via the CWinThread::m_hThread member. 通过AfxBeginThread创建的线程的句柄可以通过CWinThread::m_hThread成员获得。

Please not that synchronously blocking on a thread exit may question the idea of creating a thread in the first place. 请不要以为在线程退出时同步阻塞可能会首先质疑创建线程的想法。

Please not also that blocking a main thread, especially with an INFINITE parameter, seems a very bad idea if that thread has a GUI. 同样请注意,如果主线程具有GUI,则阻塞主线程(尤其是使用INFINITE参数)似乎不是一个好主意。

EDIT: you may be able to do a blocking wait, while processing sent message . 编辑:您可以在处理已发送消息的同时进行阻止等待。 Use the MsgWaitForMultipleObjectsEx API, with QS_SENDMESSAGE as dwWakeMask . 使用MsgWaitForMultipleObjectsEx API,将QS_SENDMESSAGE用作dwWakeMask Note that you will have to check the awakening condition an wait again if that's not the one you wait for. 请注意,如果不是等待状态,则必须再次检查唤醒条件。

I found my problem. 我发现了问题。 When Main thread stand by, in sub thread I call message and send to Main thread. 当主线程待命时,在子线程中,我调用消息并发送到主线程。 It seem to be DeadLock. 好像是死锁。

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

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