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!
I'm not a fan of threads checking boolean (or other) status variables to know when to do what, because it's wasteful. The threads would have to spin, constantly checking the variable to see if there are new instructions. This burns the CPU.
A better option is to create a semaphore or in Windows an event, and have all the threads wait on that. The threads can sleep while they arent busy, and wont steal time slices from other threads doing real work simply to check a variable.
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, ...)
QueueUserAPC()
, passing the handle to thread B and the address of a function which will throw an Exception of class MyThreadExit.WaitForSingleObjectEx
, maybe SleepEx
, or something else.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With