Is NSObject's retain method atomic?

后端 未结 1 1695
迷失自我
迷失自我 2021-02-20 01:21

Is NSObject\'s retain method atomic?

For example, when retaining the same object from two different threads, is it promised that the retain count has gone up twice, or i

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 01:53

    NSObject as well as object allocation and retain count functions are thread-safe — see Appendix A: Thread Safety Summary in the Thread Programming Guide.


    Edit: I’ve decided to take a look at the open source part of Core Foundation. In CFRuntime.c, __CFDoExternRefOperation() is the function responsible for updating the the retain counters. It tests whether the process has more than one thread and, if there’s more than one thread, it acquires a spin lock before updating the retain count, hence making this operation thread safe.

    Interestingly enough, the retain count is not an attribute (or instance variable) of an object in the struct (class) sense. The runtime keeps a separate structure with retain counters. In fact, if I understand it correctly, this structure is an array of hash tables and there’s a spin lock for each hash table. This means that a lock refers to multiple objects that have been placed in the same hash table, i.e., the lock is neither global (for all instances) nor per instance.

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