NSObject的retain方法是原子吗? [英] Is NSObject's retain method atomic?

查看:194
本文介绍了NSObject的retain方法是原子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSObject的retain方法是否原子?



例如,当从两个不同的线程保留同一个对象时,是否承诺保留计数已经增加了两次,

解决方案

div>

NSObject 以及对象分配和保留计数函数都是线程安全的 - 参见附录A:主题安全摘要中的 Thread Programming Guide






/ strong>:我决定看看Core Foundation的开源部分。在 CFRuntime.c __ CFDoExternRefOperation()是负责更新保留计数器的函数。它测试进程是否有多个线程,如果有多个线程,它会在更新保留计数之前获取一个自旋锁,从而使此操作线程安全。



有趣的是,retain count不是 struct (class)意义上的对象的属性(或实例变量)。运行时保留具有保留计数器的单独结构。事实上,如果我理解它,这个结构是一个散列表数组,每个散列表有一个自旋锁。这意味着锁指的是放置在同一哈希表中的多个对象,即锁既不是全局的(对于所有实例)也不是每个实例。


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.

解决方案

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.

这篇关于NSObject的retain方法是原子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆