Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Waiting for a thread to terminate

0.00/5 (No votes)
5 Sep 2002 1  
How to pause the main thread until a secondary thread is finished

Introduction

A few weeks ago, I had to program a custom dialog-box as part of a MSI-Setup. The code for this has to be distributed as a Regular-DLL. This dialog-box makes some actions during the initialisation and depending of the result, I had to show or not this box. The actions made were done with others threads. The problem was to wait these actions to be terminated, to first analyse the result, and then display or not the box.

The first method I've found was very simple and worked very well, but only when this DLL was used from another "normal" application. When this DLL was called from a MSI-Setup, everything went wrong.

Then I requested some help from Microsoft which gave me a few days later a solution that didn't work too!! But it gave me a good idea, and finally I found the right solution, which works on every OS and regardless which kind of application calls this DLL. It works also on multiprocessor machines.

The solution

You've to write two functions. The first one, void CMyTestDialog::PeekMessageLoop() will acquire the messages from the message queue:
void CMyTestDialog::PeekMessageLoop()
{
    MSG msg;
    while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

The second one, void CMyTestDialog::WaitForThreadToTerminate(HANDLE hThread) will take the handle of the thread we are waiting for:

void CMyTestDialog::WaitForThreadToTerminate(HANDLE hThread)
{
    DWORD dwRet;
    do
    {
        dwRet = ::MsgWaitForMultipleObjects(1, &hThread, FALSE, 
            INFINITE, QS_ALLINPUT);
        if (dwRet != WAIT_OBJECT_0)
        {
            PeekMessageLoop();
        }
    } while ((dwRet != WAIT_OBJECT_0) && (dwRet != WAIT_FAILED));
}

Sample code

Suppose you have a dialog-box with a button. When you click on it, your DLL launches an action in a secondary thread, and have to wait until this action is done. The only thing you have to do is:
void CMyTestDialog::OnButton1() 
{
    m_pUpdateThread = AfxBeginThread(UpdateDeviceContent, 
        (LPVOID)this/*, THREAD_PRIORITY_BELOW_NORMAL*/);
    if (m_pUpdateThread)
    {
        WaitForThreadToTerminate(m_pUpdateThread->m_hThread);
    }
//Do whatever you want after the action is finished

}

So I hope this article will help someone. The sample code in the zip-file is not very clean, but I think it's quite simple and everyone can understand it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here