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?
I’m new to Objective-C. When should I used @synchronized , and when should I
Share
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
NSOperationQueuespecifically. 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.NSOperationQueueis higher level and allows for directly expressing dependencies and the like.I would suggest starting with the Cocoa concurrency guide.