Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 智能指針源碼剖析(二):弱指針 wp 如何打破循環引用

編輯:關於 Android 程式設計

上一篇分析了強指針 sp,本文接著看弱指針 wp。要理解 wp 存在的意義,先要看一個必然會出事的場景。

一、循環引用:強指針的死局

假設有兩個類 CParent 與 CChild,父類持有一個指向子對象的強指針,子類也持有一個指向父對象的強指針:

class CParent : public LightRefBase<CParent> {
    sp<CChild> spc;
};
class CChild : public LightRefBase<CChild> {
    sp<CParent> spp;
};

創建 parent 與 child,令 parent.spc 指向 child、child.spp 指向 parent。此時兩個對象的引用計數都是 1。問題來了:系統一次只能析構一個對象,而每個對象都在等對方的計數歸零,於是誰都析構不掉——形成死鎖,內存洩漏。

二、wp 的定義

弱指針定義在 frameworks/rs/cpp/util/RefBase.h:

template<typename T>
class wp {
public:
    typedef typename RefBase::weakref_type weakref_type;

    inline wp() : m_ptr(0) { }

    wp(T* other);
    wp(const wp<T>& other);
    wp(const sp<T>& other);

    ~wp();

    wp& operator = (T* other);
    wp& operator = (const wp<T>& other);
    wp& operator = (const sp<T>& other);

    void set_object_and_refs(T* other, weakref_type* refs);

    // 升級為強指針
    sp<T> promote() const;

    void clear();

    inline weakref_type* get_refs() const { return m_refs; }
    inline T* unsafe_get() const { return m_ptr; }

    // 比較運算符 ...(省略)

private:
    template<typename Y> friend class sp;
    template<typename Y> friend class wp;

    T* m_ptr;
    weakref_type* m_refs;
};

與 sp 對比,wp 有三處關鍵差異:

  • 多了一個 weakref_type* 類型的成員 m_refs,指向弱引用計數器;
  • 提供了 promote() 函數,用於把 wp 臨時升級為 sp;
  • wp 指向的對象,其父類是 RefBase 而不是 LightRefBase。

三、Android 對弱引用的兩條規定

一、當強引用計數為 0 時,無論弱引用計數是否為 0,都可以釋放該對象。這一條正是循環引用能被打破的根本原因:child 對 parent 用 wp 持有,parent 的強引用計數歸零後立刻被回收,不再等待弱計數。

二、不能通過 wp 直接操作對象,必須先調用 promote() 升級為 sp。這是因為對象隨時可能已被銷毀,升級過程會原子地檢查強引用計數是否為 0,失敗則返回空指針——把「懸垂指針」問題轉化成了可判斷的空值。

四、RefBase 與引用計數器的真身

class RefBase {
public:
    void incStrong(const void* id) const;
    void decStrong(const void* id) const;
    void forceIncStrong(const void* id) const;
    int32_t getStrongCount() const;

    class weakref_type {
    public:
        RefBase* refBase() const;
        void incWeak(const void* id);
        void decWeak(const void* id);
        // 若已有強引用則獲取強引用
        bool attemptIncStrong(const void* id);
        bool attemptIncWeak(const void* id);
        int32_t getWeakCount() const;
        void printRefs() const;
        void trackMe(bool enable, bool retain);
    };

    weakref_type* createWeak(const void* id) const;
    weakref_type* getWeakRefs() const;

    typedef RefBase basetype;

protected:
    RefBase();
    virtual ~RefBase();

    enum {
        OBJECT_LIFETIME_STRONG = 0x0000,
        OBJECT_LIFETIME_WEAK    = 0x0001,
        OBJECT_LIFETIME_MASK    = 0x0001
    };
    void extendObjectLifetime(int32_t mode);

    virtual void onFirstRef();
    virtual void onLastStrongRef(const void* id);
    virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
    virtual void onLastWeakRef(const void* id);

private:
    class weakref_impl;
    weakref_impl* const mRefs;
};

LightRefBase 用一個整數 mCount 記錄引用計數,而 RefBase 沒有這樣的整數成員——它的計數器是 mRefs,一個 weakref_impl*。構造函數中完成初始化:

RefBase::RefBase()
  : mRefs(new weakref_impl(this))
{
}
class RefBase::weakref_impl : public RefBase::weakref_type {
public:
    volatile int32_t mStrong;   // 強引用計數
    volatile int32_t mWeak;     // 弱引用計數
    RefBase* const mBase;
    volatile int32_t mFlags;

#if !DEBUG_REFS
    weakref_impl(RefBase* base)
      : mStrong(INITIAL_STRONG_VALUE)
      , mWeak(0)
      , mBase(base)
      , mFlags(0)
    { }

    void addStrongRef(const void* /*id*/) { }
    void removeStrongRef(const void* /*id*/) { }
    void addWeakRef(const void* /*id*/) { }
    void removeWeakRef(const void* /*id*/) { }
    void printRefs() const { }
    void trackMe(bool, bool) { }
#else
    // ... 調試跟蹤相關實現
#endif
};

weakref_impl 定義很長,但 87 行之後都是 debug 用的,78-85 行的函數全是空實現,可以忽略。真正有內容的只有構造函數的四個初始化。其中:

#define INITIAL_STRONG_VALUE (1<<28)

強引用計數初值是個很大的數,這個偏移量的存在,使得「從無強引用到首次強引用」的判斷可以直接用計數值比較完成,不必額外分支。

五、弱引用計數的加與減

wp 的構造函數與賦值運算符:

template<typename T>
wp<T>::wp(T* other)
  : m_ptr(other)
{
    if (other) m_refs = other->createWeak(this);
}

template<typename T>
wp<T>& wp<T>::operator = (T* other)
{
    weakref_type* newRefs = other ? other->createWeak(this) : 0;
    if (m_ptr) m_refs->decWeak(this);
    m_ptr = other;
    m_refs = newRefs;
    return *this;
}

注意兩者都沒有直接操作 mWeak,而是通過 createWeak:

RefBase::weakref_type* RefBase::createWeak(const void* id) const
{
    mRefs->incWeak(id);
    return mRefs;
}

void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);                       // 空函數
    const int32_t c = android_atomic_inc(&impl->mWeak);   // 原子加一
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}

返回值 mRefs 被賦給 wp.m_refs,於是 wp 與被指向對象各自持有的指針,指向的是同一個計數器實例。

析構時對稱地減一:

template<typename T>
wp<T>::~wp()
{
    if (m_ptr) m_refs->decWeak(this);
}

void RefBase::weakref_type::decWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->removeWeakRef(id);
    const int32_t c = android_atomic_dec(&impl->mWeak);
    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
    if (c != 1) return;

    if ((impl->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
        // 常規情形:對象由最後一個強引用負責銷毀
        if (impl->mStrong == INITIAL_STRONG_VALUE) {
            // 特例:從未有過強引用,此處直接銷毀對象
            delete impl->mBase;
        } else {
            // 對象已析構,僅釋放計數器本身
            delete impl;
        }
    } else {
        // 較少見:生命週期為 OBJECT_LIFETIME_{WEAK|FOREVER}
        impl->mBase->onLastWeakRef(id);
        if ((impl->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
            delete impl->mBase;
        }
    }
}

六、強引用計數的加與減

void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);                                  // 強引用同時伴隨一個弱引用
    refs->addStrongRef(id);                             // 空函數
    const int32_t c = android_atomic_inc(&refs->mStrong);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
    if (c != INITIAL_STRONG_VALUE) {
        return;                                         // 非首次強引用,直接返回
    }
    android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);  // 扣掉偏移量,此時為 1
    refs->mBase->onFirstRef();
}

void RefBase::decStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);
    const int32_t c = android_atomic_dec(&refs->mStrong);
    ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
    if (c == 1) {
        refs->mBase->onLastStrongRef(id);
        if ((refs->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            delete this;                                // 最後一個強引用釋放,對象銷毀
        }
    }
    refs->decWeak(id);                                  // 順帶遞減弱引用計數
}

這裡有個值得留意的細節:incStrong 在增加強引用的同時也增加了一個弱引用。這保證了「只要還有人可能通過 wp 訪問對象,計數器就一定有效」,代價是每次強引用操作多一次原子遞增。

七、回到最初的問題

把 parent 對 child 的引用改為 wp,循環就被打破了:parent 析構時,其強引用計數歸零立即釋放,不必等 child 手中的弱引用;child 若此時仍要訪問 parent,promote() 會因強計數為 0 而返回空指針,代碼只需做一次空值判斷。

這就是 Android 智能指針設計的核心取捨:強指針決定對象何時死亡,弱指針決定還能不能安全地問一句「你還在嗎」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved