这篇文章与上一篇有较大的关联,没看过的可以先去看看 ^ _ ^
对象alloc后retainCount为什么引用计数为1
Person *p = [Person alloc]; // extrac = 0
// alloc出来的引用计数为多少 -- 0 -- 1
NSLog(@"%lu",(unsigned long)[p retainCount]); // 1
[p retain]; // extrac = 0 - 1
NSLog(@"%lu",(unsigned long)[p retainCount]); // extrac+1 = 2
[p release];// -1
NSLog(@"1 == %lu",(unsigned long)[p retainCount]); // 1
[p release];// 1-1 -- 引用计数位0的时候 我就析构 ? -- 响应 消息
NSLog(@" 0 == %lu",(unsigned long)[p retainCount]); // 0
[p release];// -1
NSLog(@"-1 == %lu",(unsigned long)[p retainCount]); // -1
NSLog(@"完了");
对象alloc的时候,最终会走向创建isa
并没有进行retainCount,引用计数为0,进行打印retainCount的时候由于当前引用计数为0,如果一直为0,那么对象就会被销毁,导致我们现在在做无用功,所以在
objc_object::rootRetainCount()
中有判断if (bits.nonpointer) {}
,isa初始化的时候,nonpointer为1,所以在调用retainCount时,会默认给该对象的引用计数+1。
inline uintptr_t
objc_object::rootRetainCount()
{
if (isTaggedPointer()) return (uintptr_t)this;
sidetable_lock();
isa_t bits = LoadExclusive(&isa.bits);
ClearExclusive(&isa.bits);
if (bits.nonpointer) {
uintptr_t rc = 1 + bits.extra_rc;
if (bits.has_sidetable_rc) {
rc += sidetable_getExtraRC_nolock();
}
sidetable_unlock();
return rc;
}
sidetable_unlock();
return sidetable_retainCount();
}
retain & release
retain
执行顺序
<1> - (id)retain {}
<2> objc_object::rootRetain()参数分别:false,false
<3> objc_object::rootRetain(bool tryRetain, bool handleOverflow)
<4> 判断新旧isa是否一致循环,一致就执行<9>,否则执行<5>
<5> 循环获取旧值,并赋给新值,为新值进行extra_rc+1
<6> 判断是否溢出(x86_64 256),没溢出就执行<9>,溢出走<7>
<7> 执行rootRetain_overflow,回到<3>,handleOverflow为true,下次过来时执行<8>
<8> x86_64留下引用计数的一半128,复制另一半存进去散列表
<9> return
// 并且调用retain的时候,传入的两个参数均为false
ALWAYS_INLINE id
objc_object::rootRetain(bool tryRetain, bool handleOverflow)
{
if (isTaggedPointer()) return (id)this;
bool sideTableLocked = false;
bool transcribeToSideTable = false;
isa_t oldisa;
isa_t newisa;
// 循环条件:判断是否独一份存储,对比新旧isa,如果不是,就循环
do {
transcribeToSideTable = false;
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
if (slowpath(!newisa.nonpointer)) {
ClearExclusive(&isa.bits);
if (!tryRetain && sideTableLocked) sidetable_unlock();
if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
else return sidetable_retain();
}
// don't check newisa.fast_rr; we already called any RR overrides
// 如果当前对象的isa 正在销毁
if (slowpath(tryRetain && newisa.deallocating)) {
ClearExclusive(&isa.bits);
if (!tryRetain && sideTableLocked) sidetable_unlock();
return nil;
}
//是否溢出,
//经过实验:在x86_64架构下,当newisa.extra_rc为255时,在进行addc,就会发生溢出
//溢出之后,将会拿2的7次方的extra_rc 存到散列表中,newisa.extra_rc回到128
uintptr_t carry;
//这里newisa.extra_rc 会+1 RC_ONE
newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry); // extra_rc++
printf("%lu,",newisa.extra_rc);
//newisa.extra_rc++如果溢出
if (slowpath(carry)) {
// newisa.extra_rc++ overflowed
//第一次来的话,handleOverflow是false,会进判断语句
if (!handleOverflow) {
ClearExclusive(&isa.bits);
//这里重新调用了当前方法rootRetain,但是handleOverflow = true
return rootRetain_overflow(tryRetain);
}
// Leave half of the retain counts inline and
// prepare to copy the other half to the side table.
// retry之后会来到这里
// 翻译:留下内部关联对象的一半,准备复制另一半存进去散列表
if (!tryRetain && !sideTableLocked) {
sidetable_lock();
}
sideTableLocked = true;
transcribeToSideTable = true;
newisa.extra_rc = RC_HALF;
newisa.has_sidetable_rc = true;
}
//当且仅当旧值与存储中的当前值一致时,才把新值写入存储。
} while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));
if (slowpath(transcribeToSideTable)) {
// Copy the other half of the retain counts to the side table.
// 拷贝一半(128)进散列表
sidetable_addExtraRC_nolock(RC_HALF);
}
if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
return (id)this;
}
sidetable_addExtraRC_nolock散列表添加引用计数
这个在上一篇文章,内存管理方案中已经有提到过了,这里在发一次,加点印象。
bool
objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
{
assert(isa.nonpointer);
// 通过SideTables() 获取SideTable
SideTable& table = SideTables()[this];
//获取引用计数的size
size_t& refcntStorage = table.refcnts[this];
// 赋值给oldRefcnt
size_t oldRefcnt = refcntStorage;
// isa-side bits should not be set here
assert((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
assert((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
// 如果oldRefcnt & SIDE_TABLE_RC_PINNED = 1
// 就是 oldRefcnt = 2147483648 (32位情况)
if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
//引用计数也溢出判断参数
uintptr_t carry;
// 引用计数 add
//delta_rc左移两位,右边的两位分别是DEALLOCATING(销毁ing) 跟WEAKLY_REFERENCED(弱引用计数)
size_t newRefcnt =
addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
//如果sidetable也溢出了。
//这里我for了几百万次,也没有溢出,可见sidetable能容纳很多的引用计数
if (carry) {
// 如果是32位的情况 SIDE_TABLE_RC_PINNED = 1<< (32-1)
// int的最大值 SIDE_TABLE_RC_PINNED = 2147483648
// SIDE_TABLE_FLAG_MASK = 3
// refcntStorage = 2147483648 | (oldRefcnt & 3)
// 如果溢出,直接把refcntStorage 设置成最大值
refcntStorage =
SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
return true;
}
else {
refcntStorage = newRefcnt;
return false;
}
}
release
执行顺序
<1> - (oneway void)release {}
<2> objc_object::rootRelease() 参数分别:true,false
<3> objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
<4> 判断新旧isa是否一致循环,一致就执行return,否则执行<5>
<5> 循环获取旧值,并赋给新值,为新值进行extra_rc-1
<6> 判断是否溢出,没溢出就执行return,溢出走<7> underflow
<7> 判断是否有用到散列表
<8> 从散列表中拿出RC_HALF,将这部分存进newisa
<9> 存成功就return,不成功就重试,再不行就把拿出来的放回去,然后goto retry;
<10> dealloc
ALWAYS_INLINE bool
objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
{
if (isTaggedPointer()) return false;
bool sideTableLocked = false;
//新旧isa
isa_t oldisa;
isa_t newisa;
retry:
//跟retain一样的判断条件
do {
oldisa = LoadExclusive(&isa.bits);
newisa = oldisa;
if (slowpath(!newisa.nonpointer)) {
ClearExclusive(&isa.bits);
if (sideTableLocked) sidetable_unlock();
return sidetable_release(performDealloc);
}
// don't check newisa.fast_rr; we already called any RR overrides
uintptr_t carry;
//newisa.extra_rc-1
//如果溢出的时候, newisa.extra_rc = 255
newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry); // extra_rc--
if (slowpath(carry)) {
// don't ClearExclusive()
//如果溢出走这
printf("释放溢出了,underflow\n");
goto underflow;
}
} while (slowpath(!StoreReleaseExclusive(&isa.bits,
oldisa.bits, newisa.bits)));
if (slowpath(sideTableLocked)) sidetable_unlock();
return false;
underflow:
// newisa.extra_rc-- underflowed: borrow from side table or deallocate
// abandon newisa to undo the decrement
// 重新把旧isa给新isa,意思是把引用计数-1操作还原
// 这时候的 newisa.extra_rc = 0
newisa = oldisa;
// retain的时候。如果有用到散列表,会 newisa.has_sidetable_rc = true;
if (slowpath(newisa.has_sidetable_rc)) {
printf("发现has_sidetable_rc = true \n");
// 调用release的时候handleUnderflow = false
if (!handleUnderflow) {
ClearExclusive(&isa.bits);
//类似retain时候retry,重新来一次,但是handleUnderflow为true
return rootRelease_underflow(performDealloc);
}
// Transfer retain count from side table to inline storage.
// 进判断前 sideTableLocked 没有重新赋值,所以一直是false
if (!sideTableLocked) {
ClearExclusive(&isa.bits);
sidetable_lock();
sideTableLocked = true;
// Need to start over to avoid a race against
// the nonpointer -> raw pointer transition.
// 去retry,重新回到上面,重复走一遍
goto retry;
}
// Try to remove some retain counts from the side table.
// 从散列表中拿出RC_HALF的引用计数
size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
printf("借出来的 size === %lu \n",borrowed);
// To avoid races, has_sidetable_rc must remain set
// even if the side table count is now zero.
if (borrowed > 0) {
// Side table retain count decreased.
// Try to add them to the inline count.
newisa.extra_rc = borrowed - 1; // redo the original decrement too
// 把拿出来的引用计数存到newisa
bool stored = StoreReleaseExclusive(&isa.bits,
oldisa.bits, newisa.bits);
if (!stored) {
//如果没存成功,就换个姿势再试试
// Inline update failed.
// Try it again right now. This prevents livelock on LL/SC
// architectures where the side table access itself may have
// dropped the reservation.
isa_t oldisa2 = LoadExclusive(&isa.bits);
isa_t newisa2 = oldisa2;
if (newisa2.nonpointer) {
uintptr_t overflow;
newisa2.bits =
addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow);
if (!overflow) {
stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits,
newisa2.bits);
}
}
}
if (!stored) {
// 如果还是没成功,把拿出来的放回去
// Inline update failed.
// Put the retains back in the side table.
sidetable_addExtraRC_nolock(borrowed);
goto retry;
}
// Decrement successful after borrowing from side table.
// This decrement cannot be the deallocating decrement - the side
// table lock and has_sidetable_rc bit ensure that if everyone
// else tried to -release while we worked, the last one would block.
sidetable_unlock();
return false;
}
else {
// Side table is empty after all. Fall-through to the dealloc path.
}
}
// Really deallocate.
// 如果newisa.has_sidetable_rc != true;
// 就抛错,release太多
if (slowpath(newisa.deallocating)) {
ClearExclusive(&isa.bits);
if (sideTableLocked) sidetable_unlock();
return overrelease_error();
// does not actually return
}
newisa.deallocating = true;
if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
if (slowpath(sideTableLocked)) sidetable_unlock();
__sync_synchronize();
if (performDealloc) {
((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
}
return true;
}
实验:
在这个实验中
- 我先对p retain了257次,256次保证溢出,在第257次时观察在已经使用到了sidetable的情况下的引用计数。
- 然后再对p release了260次,保证能release次数大于retain次数,保证p dealloc,并且观察在dealloc后,继续release的情况。
Person *p =[Person alloc]; // extrac = 0
NSLog(@"开始retain\n");
// 在Mac下 保证能retain溢出,并多retain一次
for (int i = 0 ; i<257; i++) {
[p retain];
}
NSLog(@"开始release\n");
// 在Mac下 保证能release溢出,并且多释放几次
for (int i = 0 ; i<260; i++) {
[p release];
}
-
然后我在源码中各个位置都做了log处理,观察进行lldb调试
-
先看retain的log
retain结论:在retain发生溢出后,会存入128到散列表,newisa的当前引用计数为128,再继续retain就在128的基础上+1。
-
看release的log ,此时p的引用计数为129(但是如果调用retainCount就会是130)
release总结:
<1> 在release发生溢出,且当前newisa的
has_sidetable_rc
为true后> <2> 走performDealloc
,将handleUnderflow
设置成true,然后再递归一次
<3> 过了handleUnderflow
这关之后,继续遇到了sideTableLocked
<4> release的时候sideTableLocked
默认为false,把sideTableLocked
设置为true后,就又要回到retry(这里应该不算递归),又走了一遍上面的一大串代码。
<5> 可谓是过关斩将遇到两个拦路虎handleUnderflow 、sideTableLocked
,过了两关后,从sidetable中拿出RC_HALF(2^7)的引用计数,-1 之后交给当前newisa.extra_rc。
TO BE CONTINUE ~