Are @ synchronized blocks guaranteed to release their locks?

Suppose these are instance methods and are called -run.

Is the lock turned off selfat the time -run?

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

- (void)run {
    @try { [self dangerous]; }
    @catch (NSException *ignored) {}
}
...
+5
source share
3 answers
Block

A is @synchronized(obj) { code }actually equivalent

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

although any particular aspect of this is just implementation details. But yes, the block is @synchronizedguaranteed to release the lock no matter how the control exits the block.

+10
source

Yes it is.

The lock selfwill be released upon completion of the process from the block @synchronized (self) {}.

+4

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

+4
source

All Articles