For a worker thread, the terminating thread can return from the thread function as a return value using the thread's exit code.
For a UI thread, because of a message loop, a wm_quit message queue is sent to the thread, which exits the message loop when the thread receives the WM_QUIT message. Therefore, the end thread can call the SDK's PostQuitMessage function inside the thread and send wm_quit messages.
The PostQuitMessage function is defined as follows:
void PostQuitMessage(int nExitCode);
which
Nexitcode: The exit code for the thread.
MFC also provides the AfxEndThread function, which both worker threads and UI threads can call the AfxEndThread function end thread inside the thread.
The AfxEndThread function is defined as follows:
void AfxEndThread(UINT nExitCode, BOOL bDelete = TRUE);
which
Nexitcode: The exit code for the thread.
In MFC's THRDCORE.CPP, the relevant code for the AfxEndThread function is as follows:
// THRDCORE.CPP
void AFXAPI AfxEndThread(UINT nExitCode, BOOL bDelete)
{
// remove current CWinThread object from memory
AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();
CWinThread* pThread = pState->m_pCurrentWinThread;
if (pThread != NULL)
{
ASSERT_VALID(pThread);
ASSERT(pThread != AfxGetApp());
// cleanup OLE if required
if (pThread->m_lpfnOleTermOrFreeLib != NULL)
(*pThread->m_lpfnOleTermOrFreeLib)(TRUE, FALSE);
if (bDelete)
pThread->Delete();
pState->m_pCurrentWinThread = NULL;
}
// allow cleanup of any thread local objects
AfxTermThread();
// allow C-runtime to cleanup, and exit the thread
_endthreadex(nExitCode);
}