Link to home
Start Free TrialLog in
Avatar of amakalski
amakalski

asked on

When MFC application terminates

I call PostQuitMessage to main UI thread of MFC, I have other threads in the app.
Will MFC app terminate or it will wait until all threads terminate ?
Avatar of AlexFM
AlexFM

All threads will be terminated. However, good programming style requires to stop all worker threads before exit. Every worker thread should have stop event associated with it. When main thread needs to stop the worker thread, it executes the following code:

SetEvent(hStopEvent);   // ask thread to exit
WaitForSingleObject(hThread, INFINITE);  // wait when thread really exits

Thread function should check stop event periodically:

while (...)   // some loop
{
    // do something

    if ( WaitForSingleObject(hStopEvent, 0) == WAIT_OBJECT_0 )  // stopped ?
        break;
}

// clean-up and return

Avatar of amakalski

ASKER

AlexFM,
Do you say that after posting QUIT msg to main UI thread, app will be terminated and other threads will be killed? Is that right?
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I apologize for providing wrong information. PostQuitMessage doesn't terminate all threads in process. It terminates only UI thread to which it posted. ExitProcess and TerminateProcess functions terminate process and all it's threads.
In any case, all worker threads should be stopped before exit using the way shown in my first post.