I'm new to Objective-C. When should I used @synchronized
, and when should I use lock/unlock
? My background is mainly in Java. I know that in Java, obtaining explicit-locks allows you to do more complex, extensive, and flexible operations (vis-à-vis release order, etc.) whereas the synchronized
keyword forces locks to be used in a block-structured way and they have also to released in the reverse order of how they were acquired. Does the same rationale hold in Objective-C?

- 94,126
- 40
- 223
- 295
2 Answers
Many would consider locking/unlocking in arbitrary order to be a bug, not a feature. Namely, it quite easily leads to deadlocks.
In any case, there is little difference between @synchonized()
, -lock/-unlock
, or any other mutex, save for the details of the scope. They are expensive, fragile, error-prone, and, often, getting them absolutely correct leads to performance akin to a single-threaded solution anyway (but with the complexity of threads).
The new hotness are queues. Queues tend to be a lot lighter weight in that they don't generally require system calls for the "fast path" operations that account for most calls. They also tend to be much more expressive of intent.
Grand Central Dispatch or NSOperationQueue
specifically. The latter is built upon the former in current OS Release. GCD's API's tend to be lower level, but they are very powerful and surprisingly simple. NSOperationQueue
is higher level and allows for directly expressing dependencies and the like.
I would suggest starting with the Cocoa concurrency guide.

- 162,346
- 23
- 271
- 359
-
Thank you! I agree with you about arbitrary locking/unlocking. I haven't found a case where I've needed to do this. Also, thank you for mentioning queues - I had no idea they had gone in that direction. I've toyed with the idea in my head and it's good to know that it is an actual and viable solution! – Vivin Paliath Aug 13 '12 at 02:13
-
Happy to help; beyond viable, just about everything is moving in the direction of queues. Queues can completely replace locks and are typically much easier to debug. – bbum Aug 13 '12 at 03:31
You are generally correct. @synchronized
takes a lock that's "attached" to a given object (the object referred to in the @synchronized
directive does not have to be a lock). As in Java, it defines a new block, and the lock is taken at the beginning, and released at exit, whether by leaving the block normally or through an exception. So, as you guessed, the locks are released in reverse order from acquisition.

- 3,608
- 1
- 21
- 28