Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,

I have 4 background threading running. I want to close application by signaling all the thread. I can wait for all the background thread using WaitForMultipleObjects, but how to signal to all running thread.

Regards
Posted
Comments
Resmi Anna 29-Mar-12 3:00am    
are you using MFC?
[no name] 29-Mar-12 3:11am    
yes!

Usually, you set up some kind of inter-thread communication in your thread procedure.
For instance, if you're using PostThreadMessage():

C++
DWORD WINAPI ThreadProc(LPVOID pX)
{
    // Cast passed pointer to what it really is.
    if (pX != NULL)
    {
        X *realPointer = reinterpret_cast<x> pX;
        // Initialize COM
        // Generate message pump
        ::PeekMessage(whatever);
        // Connect to database
        while (!done)
        {
            ::GetMessage(....)
            switch(msg.uMsg)
            {
                case WM_COMMAND: // Cast LPARAM to pointer to a Job, execute that job.
                    realPointer->ExecuteCommand(msg.lParam);
                    break;
                case WM_QUIT:// This is your cue to exith the thread.
                    done = true;
                    break;
 
            }
        } // while
        SetEvent(realPointer->reallyDone);
    } // if, scope for casted pointer.
    return 0;
}
</x>

In any case, the server thread and the client thread must be able to communicate. Google for 'thread design patterns'.

If you're using 'shoot and forget' threads, you can kill them violently, but this is a bad thing. Your best option, depending on your actual circumstances, may be to hide your main window, and just wait for all threads to complete execution.

Hope this helps,
Pablo.
 
Share this answer
 
Comments
[no name] 29-Mar-12 3:39am    
Thanks Pablo.5!
In my experience, its usually best to let a thread exit gracefully by itself. How about having some common variable that the main thread could set to false if things go awry. The second thread could periodically check this variable and if it has been set to false, it knows it should clean up and return.

I think you could use condition variables in a more elegant fashion, but his approach with the proper use of NSLock should work.
 
Share this answer
 
v2
Usually you would communicate the wish to stop by some global variable or a variable in the per-thread data block that you typically allocate to control the thread. That variable needs then to be tested in the main loop of your threads. When seeing that variable is set to false, the thread would then stop after the next iteration and after cleaning up.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900