1. MFC project scenarios are as follows:

The main thread creates a new child thread:

CWinThread *m_pThread_SysReset;

m_pThread_SysReset= AfxBeginThread(ThreadSysReset this);

The main thread calls WaitForSingleObject(m_pThread_SysReset->m_hThread, INFINITE) while waiting for the child thread to exit. The goal is for the child thread to exit safely, but the child thread is executing the SendMesage message function, and the main thread will stall. If the child thread is changed to PostMessage, it will not freeze. Why is that?

If waitforSingleObject is used on the main thread, the main thread will be blocked. If waitforSingleObject is used on the main thread, the main thread will be blocked. So the child thread doesn’t get a response, and you have suspended animation.

In fact, we can do without WaitForSingleObject because the MFC main thread does not end until it is closed, so we cannot wait with a function like WaitForSingleObject. But in many cases, we need to know about the worker thread we are creating, so we still need to know about the return value of the worker thread. So we can use the Microsoft offer MsgWaitForMultipleObjects another function.

2. How to solve the SendMessage crash problem? Use the following source code can be solved! No longer use the WaitForSingleObject, but use MsgWaitForMultipleObjects function.

This way, no matter how the child thread sends a message, SendMessage or PostMessage, it will be OK!

m_pThread_SysReset = ThreadFun_StartRun(&m_pThread_SysReset, ThreadSystemReset, this); void CViewImage::ThreadFun_ExitThread(void) { m_bExit = true; ThreadFun_WaitForObject(&m_pThread_SysReset); } CWinThread *CViewImage::ThreadFun_StartRun(CWinThread **pThread, AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority) { if (*pThread ! = NULL) { delete *pThread; *pThread = NULL; } // Start a thread, initially suspended *pThread = AfxBeginThread(pfnThreadProc, pParam, nPriority, 0, CREATE_SUSPENDED); if (*pThread ! = NULL) {// Thread does not terminate automatically (*pThread)->m_bAutoDelete = FALSE; // Restore thread running (*pThread)->ResumeThread(); } return *pThread; } void CViewImage::ThreadFun_WaitForObject(CWinThread **pThread) { if (*pThread == NULL) { return; } while (1) { DWORD result; MSG msg; result = MsgWaitForMultipleObjects(1, &(*pThread)->m_hThread, FALSE, INFINITE, QS_ALLINPUT); If (result == WAIT_OBJECT_0 + 1) {// Response to Windows message PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); TranslateMessage(&msg); DispatchMessage(&msg); } else {/ / thread end of the run (result = = WAIT_OBJECT_0) | | / / passed an invalid handle (result = = WAIT_FAILED) | | / / thread waiting time has been to (result = = WAIT_TIMEOUT) | | // Other circumstances (...) break; } } delete *pThread; *pThread = NULL; }Copy the code