Does @synchronized not use "lock" and "unlock" to achieve mutual exclusion? How does it do lock/unlock then?
The output of the following program is only "Hello World".
@interface MyLock: NSLock<NSLocking>
@end
@implementation MyLock
- (id)init {
return [super init];
}
- (void)lock {
NSLog(@"before lock");
[super lock];
NSLog(@"after lock");
}
- (void)unlock {
NSLog(@"before unlock");
[super unlock];
NSLog(@"after unlock");
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
MyLock *lock = [[MyLock new] autorelease];
@synchronized(lock) {
NSLog(@"Hello World");
}
[pool drain];
}
It just associates a semaphore with every object, and uses that.
In Objective-C, a
@synchronized
block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.Basically,
@synchronized (...)
is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.The Objective-C language level synchronization uses the mutex, just like
NSLock
does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.In particular with a
NSLock
you have an explicit lock whereas with@synchronized
you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.You can think of
@synchronized
as a compiler rewrite:is transformed into:
That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.
Apple's implementation of @synchronized is open source and it can be found here. Mike ash wrote two really interesting post about this subject:
In a nutshell it has a table that maps object pointers (using their memory addresses as keys) to
pthread_mutex_t
locks, which are locked and unlocked as needed.Actually
transforms directly into:
This API available since iOS 2.0 and imported using...