讀讀objc源碼(二):weak類(lèi)型指針的實(shí)現(xiàn)

weak指針這部分代碼寫(xiě)的很好啊,結(jié)構(gòu)清晰,接口定義到關(guān)鍵位置,讀取來(lái)很舒服。

整體結(jié)構(gòu)

weak指針管理結(jié)構(gòu).png
  • SideTable包含了引用計(jì)數(shù)表和weak指針表,大概就是內(nèi)存管理的總表,SideTable有多張,對(duì)象根據(jù)內(nèi)存地址會(huì)關(guān)聯(lián)上某一張
  • weak_table_t 包含了所有具有weak指針的對(duì)象的weak指針信息
  • weak_entry_t 對(duì)應(yīng)某一個(gè)對(duì)象,一個(gè)對(duì)象可能有多個(gè)weak指針,它們作為一個(gè)整體存放在這里
  • weak_entry_t包含兩部分,一個(gè)是對(duì)象的內(nèi)存地址,這個(gè)相當(dāng)于key/id的作用,用來(lái)識(shí)別是對(duì)應(yīng)哪個(gè)對(duì)象的;另一部分就是指向這個(gè)對(duì)象的所有weak指針。

整體的邏輯就是:
使用hash表把對(duì)象和所有指向它的weak指針關(guān)聯(lián)起來(lái),等這個(gè)對(duì)象dealloc的時(shí)候,把這些weak指針拿出來(lái),全部設(shè)置成nil。

SideTable

weak指針原理-sideTable.png

We cannot use a C++ static initializer to initialize SideTables because
libc calls us before our C++ initializers run.

代碼注釋里有句話,所以這就是為什么用靜態(tài)內(nèi)存+指針強(qiáng)轉(zhuǎn)來(lái)構(gòu)建SideTable的原因吧,要足夠早。

SideTable是用StripedMap包裝了的,StripedMap的作用,看它的讀取方法:

T& operator[] (const void *p) { 
        return array[indexForPointer(p)].value; 
    }

它重載了中括號(hào)[],從array里把值取出來(lái),關(guān)鍵就是indexForPointer這個(gè)函數(shù),它完成從指針到索引的轉(zhuǎn)換:

    static unsigned int indexForPointer(const void *p) {
        uintptr_t addr = reinterpret_cast<uintptr_t>(p);
        return ((addr >> 4) ^ (addr >> 9)) % StripeCount;
    }

所以它其實(shí)是一個(gè)hash函數(shù),根據(jù)指針的值,也就是指向內(nèi)存的地址,轉(zhuǎn)化成落在[0, StripeCount]范圍內(nèi)的一個(gè)unsigned int值。

整體來(lái)看,對(duì)一個(gè)對(duì)象,獲取它的SideTable,就是把這個(gè)對(duì)象的地址轉(zhuǎn)化成了一個(gè)[0, StripeCount]范圍內(nèi)的索引,在拿到這個(gè)索引的SideTable。

weak_table_t和weak_entry_t單看結(jié)構(gòu)沒(méi)什么特別的,在使用的時(shí)候再看。

weak指針的使用

3中情況:

  1. weakA = weakB
  2. weakA = strongB
  3. strongA = weakB

情況1和2都是調(diào)用了id objc_storeWeak(id *location, id newObj),情況3走的是id objc_loadWeakRetained(id *location),而objc_loadWeakRetained實(shí)際就是把weak對(duì)象retain了一下,屬于另外的問(wèn)題了。

還有一種情況,定義一個(gè)weak指針的時(shí)候:__weak TFBook *weakBook = nil;,這個(gè)也是走了id objc_storeWeak(id *location, id newObj)。

所以objc_storeWeak是核心的核心。

怎么看調(diào)用什么方法?猥瑣一點(diǎn),搞個(gè)while循環(huán),在里面寫(xiě)想查看的方法,然后用instrument工具里的Time Profiler看占掉cpu 100%的那個(gè)就是了!

objc_storeWeak

template <bool HaveOld, bool HaveNew, bool CrashIfDeallocating>
static id 
storeWeak(id *location, objc_object *newObj)
  • HaveOld 是否有就對(duì)象,weakA = weakB,如果weakA之前是nil,那HaveOld就是false.
  • HaveNew 是否新對(duì)象
  • 這個(gè)操作處在deallocing調(diào)用過(guò)程中是否奔潰
  • location是指向weak指針的指針,因?yàn)橐薷膚eak指針
  • newObj新對(duì)象

它的作用就是解除舊對(duì)象關(guān)系,和新對(duì)象建立聯(lián)系。

storeWeak函數(shù).png
weak_unregister_no_lock:
.....
if ((entry = weak_entry_for_referent(weak_table, referent))) {
        remove_referrer(entry, referrer);
.....
if (empty) {
            weak_entry_remove(weak_table, entry);
        }
.....

取出entry,移除referrer,referrer是weak指針的引用,這里的weak_table是舊表,舊表里移除weak指針,就是解除了久對(duì)象和weak指針的關(guān)系。

如果這個(gè)empty空了,就從table里去掉。

  • weak_entry_for_referent

    size_t begin = hash_pointer(referent) & weak_table->mask;
    ...
    while (weak_table->weak_entries[index].referent != referent) {
          index = (index+1) & weak_table->mask;
          if (index == begin) bad_weak_table(weak_table->weak_entries);
          hash_displacement++;
          if (hash_displacement > weak_table->max_hash_displacement) {
              return nil;
          }
      }
    

    從weak_table_t里面取出entry,用了hash表的邏輯:

    • hash_pointer也是使用指針地址,映射到一個(gè)索引。&weak_table->mask這個(gè)操作是?這個(gè)mask實(shí)際值是表的size-1,而size是2的n次方方式擴(kuò)張的,所以mask的形式就1111 1111 1111這種,索引和mask位與之后的值必定就落在了[0, size]范圍內(nèi)。簡(jiǎn)潔高效,牛逼!
    • index都取到了,為什么還要while循環(huán)?因?yàn)閔ash函數(shù)也會(huì)重合的,如果index1的位置已經(jīng)有人占了,又來(lái)一個(gè)人要占index1怎么辦?往后挪,直到找到一個(gè)空位置。所以hash函數(shù)得到的index和實(shí)際位置有那么一點(diǎn)的偏差。
    • hash_displacement是在存入數(shù)據(jù)的時(shí)候記錄了最大的偏差值,有這個(gè)做把控,偏移超過(guò)了這個(gè)值肯定是沒(méi)有了。
  • remove_referrer

if (! entry->out_of_line()) {
       for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
           if (entry->inline_referrers[i] == old_referrer) {
               entry->inline_referrers[i] = nil;
               return;
           }
       }
.....
size_t begin = w_hash_pointer(old_referrer) & (entry->mask);
....
while (entry->referrers[index] != old_referrer) {
       index = (index+1) & entry->mask;
       if (index == begin) bad_weak_table(entry);
       hash_displacement++;
       if (hash_displacement > entry->max_hash_displacement) {
          .....
           objc_weak_error();
           return;
       }
   }

weak_entry_t有個(gè)奇怪的地方就是里面有個(gè)union:

union {
        struct {
            weak_referrer_t *referrers;
            uintptr_t        out_of_line_ness : 2;
            uintptr_t        num_refs : PTR_MINUS_2;
            uintptr_t        mask;
            uintptr_t        max_hash_displacement;
        };
        struct {
            // out_of_line_ness field is low bits of inline_referrers[1]
            weak_referrer_t  inline_referrers[WEAK_INLINE_COUNT];
        };
    };

這兩個(gè)東西都是用來(lái)存儲(chǔ)指向這個(gè)對(duì)象的所有weak指針的,但是是不同時(shí)期使用的,到weak指針在4(WEAK_INLINE_COUNT)個(gè)以?xún)?nèi)的時(shí)候,用數(shù)組inline_referrers,超過(guò)用weak_referrer_t,這個(gè)還是hash表。

我的理解是這是為了性能考慮。一般情況,就一兩個(gè)weak指針會(huì)指向同一個(gè)對(duì)象,用數(shù)組管理,存取快。但是也得允許N多weak指針指向同一個(gè)對(duì)象,WEAK_INLINE_COUNT不可能無(wú)限大。感受到了一點(diǎn)空時(shí)間、分階段處理的思想。

weak_referrer_t的存取跟上面weak_table_t一樣。

out_of_line是用來(lái)判斷是否超過(guò)數(shù)組個(gè)數(shù)的,就是它用來(lái)做兩種方案的切換:

    bool out_of_line() {
        return (out_of_line_ness == REFERRERS_OUT_OF_LINE);
    }

out_of_line_ness是否被設(shè)置了REFERRERS_OUT_OF_LINE這個(gè)標(biāo)識(shí)。這個(gè)標(biāo)識(shí)的值實(shí)際是2。注釋里有一段話:

// out_of_line_ness field overlaps with the low two bits of inline_referrers[1].
// inline_referrers[1] is a DisguisedPtr of a pointer-aligned address.
// The low two bits of a pointer-aligned DisguisedPtr will always be 0b00
// (disguised nil or 0x80..00) or 0b11 (any other address).
// Therefore out_of_line_ness == 0b10 is used to mark the out-of-line state.

因?yàn)閡nion的關(guān)系,out_of_line_ness的內(nèi)存位置對(duì)應(yīng)的就是數(shù)組inline_referrers里第二個(gè)(weak_referrer_t和weak_referrer_t *都是8個(gè)字節(jié))。根據(jù)這段注釋?zhuān)瑆eak_referrer_t的數(shù)據(jù)的二進(jìn)制結(jié)尾要么是00要么是11,不會(huì)是10,所以用10來(lái)做標(biāo)識(shí)。

如果只使用inline_referrers,那么out_of_line_ness讀取出來(lái)就要么是00要么是11,所以如果讀出來(lái)是10,也就是十進(jìn)制2,就是使用hash表的referrers。

我沒(méi)搞懂的是為什么weak_referrer_t的結(jié)尾不會(huì)是10。

weak_register_no_lock

這個(gè)函數(shù)和weak_unregister_no_lock幾乎就是反操作了:

weak_entry_t *entry;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        append_referrer(entry, referrer);
    } 
    else {
        weak_entry_t new_entry(referent, referrer);
        weak_grow_maybe(weak_table);
        weak_entry_insert(weak_table, &new_entry);
    }
  • weak_grow_maybe+weak_entry_insert對(duì)應(yīng)weak_entry_remove
  • append_referrer對(duì)應(yīng)remove_referrer

總結(jié)

  • 使用hash表把對(duì)象和所有指向它的weak指針關(guān)聯(lián)起來(lái),等這個(gè)對(duì)象dealloc的時(shí)候,把這些weak指針拿出來(lái),全部設(shè)置成nil。
  • 3層表:side table+weak table--->weak entry---> referrers + inline_referrers
  • hash表的使用邏輯
  • referrers和inline_referrers的切換
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容