I want to check a global bool
value in my thread whenever necessary: If it's true
the thread should exit, and the thread should continue if it's false
.
While checking, I could be inside a single function or I could be within a nested function. I need to ensure that I return to the main function first, then return 0
in the main function, which seems very stupid.
So the only way I can think of is to throw
an exception when the condition is fulfilled and then catch it at the end of this thread, so that all the elements are destructed correctly.
So is there a more standard way in C++ language to do this? How do you exit a thread while you are in a nested function?
Your approach is fine. Compared to the costs of thread creation and destruction, throwing an exception is negligible.
If for some reasons you aren't allowed to use exceptions:
Check that signaling variable several places in your code. Note that regular code runs pretty damn fast so you only need these checks inside/before long calculations (loops) or IO operations that could block. Make sure the rest of the code doesn't depend on the results of some unfinished calculations.
Use a coding style where you always return an error code from every function (at least for this thread).