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

前端 未结 2 1061
别跟我提以往
别跟我提以往 2021-01-02 05:45

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

相关标签:
2条回答
  • 2021-01-02 06:19

    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.

    0 讨论(0)
  • 2021-01-02 06:37

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

    0 讨论(0)
提交回复
热议问题