Todd Ditchendorf
Todd Ditchendorf

Reputation: 11337

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?

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

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

Upvotes: 5

Views: 524

Answers (3)

Lily Ballard
Lily Ballard

Reputation: 185671

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.

Upvotes: 10

Rick
Rick

Reputation: 3857

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

Upvotes: 4

Nekto
Nekto

Reputation: 17877

Yes, it is.

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

Upvotes: 4

Related Questions