Post by Dan Berghult
RB2012r2.1 Mac and Win
I have an app where you can configure several tasks.
Each tasks are then performed by an RB thread.
That is if the task is sleeping: Just kill it and if the thread is running: wait a while then kill the thread.
The approach that I use today is to run another thread which tries to stop the task-threads and sits and waits to kill the long running threads and finally quits the application.
I guess my question is: Should I do this in another way instead? (Timer perhaps)
Or is this the right approach?
Rule #1 of multi-threading: You should NEVER, EVER, EVER (EVER times infinity!) "kill" a thread from outside the thread. That thread *could* have one or more resources "locked" or in-use, and killing the thread means that resource is locked for everyone (or left open instead of being properly closed).
Rule #2 of multi-threading: If you really believe that you have a valid reason for killing one thread from another thread, refer to rule #1.
That being said, you *should* have a "terminate" flag as a part of your thread object, and check it "often" (you decide what "often" means) within the thread. If your thread code detects that the flag is set, terminate as quickly as you can after leaving resource states as unchanged as possible. This way, the thread is in charge of its own clean-up, and you can guarantee proper termination and state. Remember that a computer's reaction to an input may be far faster than the user's -- most users won't consider a 0.1-0.2 second delay in response to be "laggy" -- except in games.
Personally, my threads make copies of data that the thread depends upon early in the thread's execution and does all of its work in local variables. When the thread operation is complete, it "pushes" its changes back to the main object so that the object states are maintained and there's no "intermediate" state (some of the data is changed, some isn't). Of course, all of this "getting" and "setting" is wrapped inside a CriticalSection-based mutex so that the get and set operations within the thread don't get an indeterminate state, and array contents are copied (so are objects that could change throughout the run of the thread). Yes, this does mean a bit more work, but my threads don't deadlock or work with data that is invalid (it could be stale, but that's a different problem entirely
Multi-threading isn't easy, but RS does make it easier than it could be.
Glenn L. Austin, Computer Wizard and Race Car Driver <><
Unsubscribe or switch delivery mode:
Search the archives: