207

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];
}
David Lin
  • 5,538
  • 4
  • 25
  • 23
  • Note: Related to http://stackoverflow.com/questions/1215765/ – Quinn Taylor Aug 01 '09 at 04:32
  • 10
    You don't need to override init if you don't need it. The runtime automatically calls the superclass' implementation if you don't override a method. – Constantino Tsarouhas Aug 12 '11 at 23:57
  • 3
    An important thing to note is that the above code isn't synchronized. The `lock` object is created on every call, so there will never be a case where one `@synchronized` block locks out another. And this means there's no mutual exclusion.) Of course, the above example is doing the operation in `main`, so there's nothing to exclude anyway, but one should not blindly copy that code elsewhere. – Hot Licks Jan 26 '15 at 12:48
  • 4
    After reading this SO page, I decided to investigate @synchronized a little more thoroughly and write a blog post on it. You may find it useful: http://rykap.com/objective-c/2015/05/09/synchronized/ – rjkaplan Mar 18 '16 at 21:52

5 Answers5

336

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:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

tchrist
  • 78,834
  • 30
  • 123
  • 180
Louis Gerbarg
  • 43,356
  • 8
  • 80
  • 90
  • 18
    You're also forgetting the exception handling that @synchronized does for you. And as I understand it, much of this is handled at runtime. This allows for optimization on uncontended locks, etc. – Quinn Taylor Aug 01 '09 at 01:18
  • 7
    Like I said, the actual generated stuff is more complex, but I didn't feel like writing section directives in order build the DWARF3 unwind tables ;-) – Louis Gerbarg Aug 01 '09 at 01:33
  • And I can't blame you. :-) Also note that OS X uses Mach-O format instead of DWARF. – Quinn Taylor Aug 01 '09 at 05:11
  • 6
    No one uses DWARF as a binary format. OS X does use DWARF for debug symbols, and it uses DWARF unwind tables for zero cost exceptions – Louis Gerbarg Aug 01 '09 at 14:49
  • 9
    For reference, I have written compiler backends for Mac OS X ;-) – Louis Gerbarg Aug 01 '09 at 14:50
  • @LouisGerbarg You are the guy I want to be in five years. :-D – Zhigang An Oct 16 '17 at 17:29
  • @LouisGerbarg You said about "implicit lock associated with object". Can I just pass any lock as a parameter of @synchornized? If so, `@synchronized(self.class.someLock)` will be as fast as a mutex, right? There is zero cost for it?.. – gaussblurinc Jul 22 '19 at 19:35
44

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.

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
  • 1
    That link has expired. Here's the updated link: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html – Ariel Steiner Mar 29 '20 at 11:39
33

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>
james_womack
  • 10,028
  • 6
  • 55
  • 74
Dirk Theisen
  • 331
  • 3
  • 2
3

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.

JP Illanes
  • 3,665
  • 39
  • 56
-4

It just associates a semaphore with every object, and uses that.

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
  • Technically, it creates a mutex lock, but the basic idea is correct. See the Apple diva at: http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW16 – Mark Bessey Aug 01 '09 at 00:13
  • 4
    Not just a mutex, but a recursive lock. – kperryua Aug 01 '09 at 01:09