Is it possible to use a timer to kill rogue method in background thread?

158 Views Asked by At

I have a piece of code that calls a method (i.e. processRegex) which is from a 3rd party library, regexKitLite, that runs a regex match on a bunch of data. I am running this method in a bg thread using performSelectorInBackground:. I have found that in some cases if the data is invalid or corrupted then the processRegex method locks up the thread and gets caught in a recursive loop which could take forever to come back which i obv would like to avoid.

I was thinking of using a timer that basically waits x amount of time and if it hasnt been invalidated before the specified time passes it then kills the bg thread that is running the method.

My problem however is:

I cant launch the timer in the same thread as the regex method because that thread could lock up while trying to process the data and wouldnt call my timer as i tried below.

// setup timer to restrict the amount of time a regex can take before killing it
myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(resultProcessingTimedOut:) userInfo:nil repeats:NO];

resultsArray = [NSMutableArray arrayWithArray:[html arrayOfCaptureComponentsMatchedByRegex:]; // <-- could lock up thread!!

[myTimer invalidate];

Secondly, according to the apple docs you have to invalidate the timer in the same thread that started it and i cant launch the timer in its own background thread because im not sure how i would then invalidate it?

Lastly, how would i even kill the thread that is running the regex as you are not supposed to terminate threads.

Any ideas on how to deal with this situation???

thx

1

There are 1 best solutions below

0
On BEST ANSWER

In short, no, you cannot kill another thread arbitrarily. There is no way to know what state it'll be in when killed and, thus, the memory leaks and/or corruption are bound to happen.

You can solve this in one of several ways (including combining):

  • modify the regexkit to have some kind of "stop" flag that can be set after the timer fires in another thread. Periodically check it and clean up / stop when needed.

  • validate or limit the input regular expression and input data to ensure that the slow/long situation doesn't happen

  • break up the input data such that you can batch process it.