开发者

Are @synchronized blocks guaranteed to release their locks?

开发者 https://www.devze.com 2023-04-12 15:32 出处:网络
Assume these are instance methods and -run is called. Is the lock on self released by the time -run returns?

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

精彩评论

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

关注公众号