Effective exit from a multithreaded application (specifics)

I read several sources about the correct methods of message bubbling from a thread to all other threads in order to complete the grace (each thread performs its own exit procedure). Of these, I liked the idea of ​​a global atomic boolean that can be tagged from any thread, and all other threads check this flag to perform the exit procedure - when all threads are connected, the main thread can then exit the application.

Net computing threads are likely to be handled differently, right?

Is it effective and safe? Is there a better way to do this?

Thanks!

+6
c ++ multithreading parallel-processing exit
source share
2 answers

On Windows, I use QueueUserAPC to call a function that throws an exception, which will cause threads to execute cleanly.

I wrote more details in this answer:

How can I guarantee a quick shutdown of my win32 application?

In short, this is what happens:

Say thread A wants to end thread B (and then C, D, ...)

  • Thread A calls QueueUserAPC() , passing the handle to thread B and the address of the function that throws the MyThreadExit class exception.
  • Thread B runs fine until it calls something that checks for warning expectations. Maybe WaitForSingleObjectEx , maybe SleepEx , or something else.
  • At this point, thread B starts the previously passed APC function, causing the exception to be thrown in Thread B.
  • All objects distributed over the stacks are automatically automatically destroyed, since the exception makes thread B "expand" its stack.
  • The outermost stream function from stream B will catch an exception.
  • Thread B is now shutting down, possibly signaling this to Thread.
+1
source share

I'm not a fan of threads checking boolean (or other) state variables to know when to do what, because it is wasteful. The threads would have to spin, constantly checking the variable to see if there are any new instructions. It burns the processor.

The best option is to create a semaphore or Windows event, and all threads expect this. Threads can sleep while they are not busy, and do not steal temporary fragments from other threads that do the real work, just to check the variable.

+4
source share

All Articles