简体   繁体   中英

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. 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.

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.

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.

EDIT: you may be able to do a blocking wait, while processing sent message . Use the MsgWaitForMultipleObjectsEx API, with QS_SENDMESSAGE as 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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