209

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];
}
4
  • Note: Related to www.greatytc.com/questions/1215765 Commented Aug 1, 2009 at 4: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. Commented Aug 12, 2011 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
    Commented Jan 26, 2015 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: rykap.com/objective-c/2015/05/09/synchronized
    – rjkaplan
    Commented Mar 18, 2016 at 21:52

5 Answers 5

338

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.

7
  • 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. Commented Aug 1, 2009 at 1: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 ;-) Commented Aug 1, 2009 at 1:33
  • And I can't blame you. :-) Also note that OS X uses Mach-O format instead of DWARF. Commented Aug 1, 2009 at 5: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 Commented Aug 1, 2009 at 14:49
  • 10
    For reference, I have written compiler backends for Mac OS X ;-) Commented Aug 1, 2009 at 14:50
45

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.

1
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>
5
  • So it provides no support for cleanly handling thrown exceptions?
    – Dustin
    Commented Feb 14, 2012 at 18:55
  • Is this documented somewhere?
    – jbat100
    Commented Apr 13, 2012 at 13:21
  • 6
    There's an unbalanced brace there. Commented Jul 11, 2012 at 8:19
  • 1
    @Dustin actually it does, from the docs: "As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown."
    – Pieter
    Commented Sep 3, 2013 at 8:34
  • objc_sync_enter probably will use pthread mutex, so Louis's transform is deeper and correct.
    – jack
    Commented Dec 6, 2014 at 21:55
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.

-4

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.