Reputation: 171
I have more of a high level question.
I have some section of code (pseudo code):
{
functioncall1();
functioncall2();
functioncall3();
functioncall4();
functioncall5();
}
That happens when an event/thread triggers. In a separate event, I need to stop all further things from executing:
{
stopAllExecution();
}
I don't know how to do this, besides changing the original event to:
{
if (executionHasStopped) {
functioncall1();
}
if (executionHasStopped) {
functioncall2();
}
if (executionHasStopped) {
functioncall3();
}
if (executionHasStopped) {
functioncall4();
}
if (executionHasStopped) {
functioncall5();
}
}
I don't want to litter my code with these checks everywhere, but I can't think of another way to halt execution.
I am running in Delphi, if that is important.
Anyone know of a better way to achieve this?
Upvotes: 2
Views: 119
Reputation: 23036
Ordinarily the safe way to do this is to structure the code in your threads such to periodically check the state of some signal and cleanly exit when an exit condition is set.
For threads that are processing sets of data using a loop this is relatively straightforward; introduce a check for the exit condition before/after each iteration of the loop and abort the loop if set.
For threads that are simply performing a series of steps you have no choice but to introduce checks for that exit condition at appropriate points in those steps and only proceeding if not set; i.e. it does unfortunately mean "littering your code" with the check, as it were.
However, depending on the operations being performed by the threads, there is a "Nuclear Option", in the form of the TerminateThread Api.
Conditions apply to the use of this Api (read the docs) and there are important considerations in terms of managing any resources that may be acquired and/or owned by the threads if they are terminated using this approach since they will be provided with no opportunity to clean-up or release any such resources.
But, as long as the threads in your case may be safely terminated pre-emptively, this would provide the inversion of control you are looking for, allowing a supervisory thread to terminate worker threads without those worker threads having to implement any termination/exit event checks.
This is not intended to constitute a recommendation to use this approach, only to inform you as to its existence. Whether it is suitable or appropriate in your case is impossible to say without intimate knowledge of the specifics of your code; only you can decide.
Upvotes: 2