同步块是否保证释放它们的锁

同步块是否保证释放它们的锁

本文介绍了@同步块是否保证释放它们的锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这些是实例方法,并且调用 -run

Assume these are instance methods and -run is called.

是时间 -run self c>返回?

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

...
- (void)dangerous {
    @synchronized (self) {
        [NSException raise:@"foo" format:@"bar"];
    }
}

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


推荐答案

A @synchronized(obj){code} block实际上等效于

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

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

虽然这里的任何特定方面只是实现细节。但是,无论控制是否退出块, @synchronized 块都保证释放锁。

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.

这篇关于@同步块是否保证释放它们的锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:56