NSObject的retain方法是原子的吗?
NSObject的retain方法是原子的吗?
例如,当从两个不同的线程保留同一个对象时,是否允许保留计数增加两次,或者保留计数是否可以只增加一次?
谢谢。
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 is it possible for the retain count to be incremented just once?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSObject
以及对象分配和保留计数函数都是线程安全的 - 请参阅 附录 A:线程安全摘要,位于 线程编程指南。编辑:我决定看一下 Core Foundation 的开源部分。在 CFRuntime.c 中,
__CFDoExternRefOperation()
是函数负责更新保留计数器。它测试进程是否有多个线程,如果有多个线程,它会在更新保留计数之前获取自旋锁,从而使该操作成为线程安全的。有趣的是,保留计数并不是 struct(类)意义上的对象的属性(或实例变量)。运行时保留带有保留计数器的单独结构。事实上,如果我理解正确的话,这个结构是一个哈希表数组,每个哈希表都有一个自旋锁。这意味着锁指的是已放置在同一个哈希表中的多个对象,即锁既不是全局的(对于所有实例)也不是针对每个实例的。
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.