Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSThread sleep in an NSOperation

Working with some code, I'm coming across run loops, which I'm new to, inside NSOperations.

The NSOperations are busy downloading data - and whilst they are busy, there is code to wait for the downloads to complete, in the form of NSRunLoops and thread sleeping.

This code in particular is of interest to me:

while (aCertainConditionIsTrue && [self isCancelled]==NO) {
     if(![[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]){
        [NSThread sleepForTimeInterval:1.0];
     }
}

I've read about the run loops, and runMode:beforeDate: will wait for an input source or a timeout. Although I'm not 100% what counts as an input souce.

On the first execution of this it always returns NO and hits the sleepForTimeInterval:. Is this bad?

In a particular utility class, it's hitting the sleepForTimeInterval: a lot - once for each thread - which significantly hurts the performance.

Any better solutions for this, or advice?

like image 837
bandejapaisa Avatar asked Jan 19 '12 14:01

bandejapaisa


1 Answers

Sleeping locks up the thread. Perhaps you change your code to use performSelector:withObject:afterDelay. That way your thread can continue to run.

    ...
    done = NO;
    [self checkDoneCondition:nil];
    ...

- (void)checkDoneCondition:(id)object {
    if (aCertainConditionIsTrue && [self isCancelled]==NO) {
        if(...) {
            [self performSelector:@selector(checkDoneCondition:) withObject:[con error] afterDelay:1.0];
        } else {
            done = YES;
        }
    }
}
like image 100
jimmyg Avatar answered Sep 25 '22 10:09

jimmyg