开发者

Do not wait on @synchronized in objectictive-c

I have timer that once in a minute executes a method. The method has some code and call to NSThread. NSthread calls another method with critical section.

Sometimes it takes more than a minute to execute critical section. And i need in case another thread reaches @synchronized not to wait, but exit function without executing code.

Currently i do it in a way that seems not working propertly and two threads seem to enter critical section.

The code:

BOOL isRunning;
- (void)mainFunction
{
    isRunning = NO;
    [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(glichyFunc) userInfo:nil repeates:YES];
}
- (void)glichyFunc
{
    a++;
    b--;
    [NSThread detachNewThreadSelector:@selector(doJob) toTarget:self withObject:nil];     
}
- (开发者_开发百科void)doJob
{
    if (isRunning)
        return;

    isRunning = YES;

    @syncronized{
         c = [globalObject calculate];
         isRunning = NO;
    }
}


You could roll your implementation around the use of NSLock and -tryLock. You will then be able to check if the lock is available and avoid blocking if it's currently locked by another thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜