這篇文章與上一篇有較大的關聯,沒看過的能夠先去看看 ^ _ ^c++
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 bash
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();
}
複製代碼
執行順序 <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; } 複製代碼
這個在上一篇文章,內存管理方案中已經有提到過了,這裏在發一次,加點印象。ide
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;
}
}
複製代碼
執行順序 <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> deallocui
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;
}
複製代碼
###實驗: 在這個實驗中this
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調試 spa
先看retain的log 翻譯
retain結論:在retain發生溢出後,會存入128到散列表,newisa的當前引用計數爲128,再繼續retain就在128的基礎上+1。3d
看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 ~