views:

202

answers:

1

The documentation for properties in Obj-C 2.0 say that atomic properties use a lock internally, but it doesn't document the specifics of the lock. Does anybody know if this is a per-property lock, a per-object lock separate from the implicit one used by @synchronized(self), or the equivalent of @synchronized(self)?

+3  A: 

The lock used by atomic @properties is an implementation detail--for appropriate types on appropriate platforms, atomic operations without a lock are possible and I'd be surprised if Apple was not taking advantage of them. There is no public access to the lock in any case, so you can't @synchronize on the same lock. Several Apple engineers have pointed out that atomic properties do not guarantee thread safety; atomic properties only guarantee that gets/sets of that value are atomic. For correct thread safety, you will have to make use of higher-level locking or synchronization and you almost certainly would not want to use the same lock as the synthesize getter/setter(s) might be using.

Barry Wark
Yep, see "man atomic".
Nikolai N Fetissov
Ok. I was asking because I was wondering if there would be extra overhead to using both atomic properties and a @synchronized() when dealing with multiple properties at the same time. It sounds like, for operations that can't be done using an atomic primitive, there will be extra overhead as it effectively uses 2 locks. Ah well.
Kevin Ballard
In this case, when you are already using a @synchronized or otherwise protected block to implement higher-level locking semantics, it may make sense to use nonatomic for your properties.
Barry Wark
I don't want to make all clients of the code have to use @synchronized blocks just to access the properties, nor do I want to implement my own getters/setters just to use @synchronized instead of the synthesized synchronization operations.
Kevin Ballard
If you're using higher-level synchronization to order access to the resources containing those properties, but you allow other clients direct access to those properties, it may be very hard to guarantee proper behavior of your multithreaded code that's reliant on those higher level synchronizations to order things. YMMV, of course, but be wary. There be dragons there.
Barry Wark
I ended up not even using @synchronized but rather a few explicit NSLock objects (for locking individual private ivars), and I rely on ordering of property access instead. I believe the way I've ordered the property assignments, the client always has a usable view of the object even from another thread (e.g. the image can be set if it's not marked finished, but if it's marked finished, the image will always be set).
Kevin Ballard