Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking details of synthesized atomic @properties in Obj-C 2.0

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)?

like image 574
Lily Ballard Avatar asked May 27 '09 20:05

Lily Ballard


People also ask

What is atomic Nonatomic in Objective-C?

In Objective-C the implementation of an atomic property allows properties to be safely read and written from different threads. For nonatomic properties, the underlying pointer of a read value could be released when a new value is being written at the same time.

What is the difference between atomic and nonatomic properties which is the default for synthesized properties?

Atomic means only one thread accesses the variable (static type). Atomic is thread-safe, but it is slow. Nonatomic means multiple threads access the variable (dynamic type). Nonatomic is thread-unsafe, but it is fast.

What is the difference between atomic and non atomic synthesized properties in Swift?

Defining a property as atomic should guarantee that it can be safely read and written from different threads. Non-atomic properties have no guarantee regarding the returned value, but they come with enhanced speed of accessing these properties. Note: Property atomicity is not synonymous with an object's thread safety.

What is synthesize in Objective-C?

@synthesize tells the compiler to take care of the accessor methods creation i.e it will generate the methods based on property description. It will also generate an instance variable to be used which you can specify as above, as a convention it starts with _(underscore)+propertyName.


1 Answers

Looking at the generated code (iOS SDK GCC 4.0/4.2 for ARM),

  • 32-bit assign properties (including struct {int32_t v;}) are accessed directly.
  • Larger-than-32-bit structs are accessed with objc_copyStruct().
  • double and int64_t are accessed with objc_copyStruct, except on GCC 4.0 where they're accessed directly with stmia/ldmia (I'm not sure if this is guaranteed to be atomic in case of interrupts).
  • retain/copy accessors call objc_getProperty and objc_setProperty.

Cocoa with Love: Memory and thread-safe custom property methods gives some details on how they're implemented in runtime version objc4-371.2; obviously the precise implementation can vary between runtimes (for example, on some platforms you can use atomic swap/CAS to spin on the ivar itself instead of using another lock).

like image 157
tc. Avatar answered Sep 19 '22 07:09

tc.