c++multithreadingparallel-processingexit

Efficient exit from multithreaded application (specifics)


I've read a few sources on proper methods of bubbling a message out from a thread to all other threads to exit gracefully (every thread performs it's own exit routine). Of these, I liked the idea of a global atomic boolean that can be flagged from any thread, and all other threads check this flag to perform an exit routine - when all threads are joined, the main thread can then exit the application.

Purely computation threads would probably be handled differently, right?

Is this efficient and safe? Is there a better way to do this?

Thanks!


Solution

  • In Windows, I use QueueUserAPC to call a function which throws an exception, causing threads to exit cleanly.

    I wrote more about the details in this answer here:

    How do I guarantee fast shutdown of my win32 app?

    In summary, here's what happens:

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