How to safely terminate a thread

Source: Internet
Author: User

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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.