开发者

Are @synchronized blocks guaranteed to release their locks?

Assume these are instance methods and -run is called.

Is the lock on self released by the time -run returns?

开发者_如何学Go...
- (void)dangerous {
    @synchronized (self) {
        [NSException raise:@"foo" format:@"bar"];
    }
}

- (void)run {
    @try { [self dangerous]; }
    @catch (NSException *ignored) {}
}
...


A @synchronized(obj) { code } block is effectively equivalent to

NSRecursiveLock *lock = objc_fetchLockForObject(obj);
[lock lock];
@try {
    code
}
@finally {
    [lock unlock];
}

though any particular aspect of this is really just implementation details. But yes, a @synchronized block is guaranteed to release the lock no matter how control exits the block.


Yes, it is.

Lock on self will be released after your process goes out from @synchronized (self) {} block.


Yes, the lock is released when -dangerous returns (even via exception). @synchronized adds an implicit exception handler to release the mutex.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜