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

深入 Android Framework:SP、RefBase、weakref_impl 與 Thread 類解析

編輯:關於 Android 程式設計

翻閱 Android Framework 的原始碼時,你會發現 SP 智慧指針幾乎無所不在。初學時我常把它單純當成普通指針使用,卻忽略了它內在的精妙設計。本文就帶大家一起梳理 SP 類及其相關機制(RefBase、weakref_impl、Thread)的運作原理。

一、SP 是一個模板類

SP 的本質是一個模板類,其內部維護一個 T* m_ptr 成員變量,真正指向我們 new 出來的物件。以下是它的結構:

template <typename T>
class sp {
public:
    inline sp() : m_ptr(0) { }
    sp(T* other);
    sp(const sp<T>& other);
    template<typename U> sp(U* other);
    template<typename U> sp(const sp<U>& other);
    ~sp();
    sp& operator = (T* other);
    sp& operator = (const sp<T>& other);
    template<typename U> sp& operator = (const sp<U>& other);
    template<typename U> sp& operator = (U* other);
    void clear();
    inline T& operator* () const { return *m_ptr; }
    inline T* operator-> () const { return m_ptr; }
    inline T* get() const { return m_ptr; }
    // COMPARE(==) COMPARE(!=) COMPARE(>) COMPARE(<) COMPARE(<=) COMPARE(>=)
private:
    template<typename Y> friend class sp;
    T* m_ptr;
};

以 sp<A> mA = new A(); 為例,其構造函數如下:

template<typename T>
sp<T>::sp(T* other) : m_ptr(other) {
    if (other) other->incStrong(this);
}

new 出來的 A 物件被存入 sp 的成員變量中,同時會呼叫 A 的 incStrong 方法。這就牽涉到 RefBase 類——它是比 sp 更為常見的基類。

二、RefBase 與 weakref_impl 的關係

當我們自訂的類 A 繼承自 RefBase,就能使用其 incStrong 函數。先看 RefBase 的構造函數:

RefBase::RefBase() : mRefs(new weakref_impl(this)) { }

mRefs 被賦值為一個 weakref_impl 物件(又稱影子物件),並傳入 this,也就是剛才 new A() 的物件。接著看 weakref_impl 的構造:

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

這裡的 mBase 是一個 RefBase 類指標,指向類 A 的實際物件。依 C++ 多態知識,透過基類指標 mBase 就能訪問類 A 重載的虛函數。

回過頭看 incStrong 的實作:

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);
    refs->mBase->onFirstRef(); // mBase 維護著繼承類實際物件 this 指標
}

它增加了指針的引用計數,而最值得關注的是最後一行:當首次建立 sp<A> mA 時,會觸發 mBase->onFirstRef(),也就是所謂的第一次引用。我們通常在自訂類中重載 onFirstRef(),在其中進行必要的初始化。

三、Android Native 的 Thread 類

在 onFirstRef 中經常會遇到 run 函數,這是啟動新執行緒的方法,前提是類 A 繼承了 Thread 類。Thread 有幾個核心函數,其中最重要的就是 run:

status_t Thread::run(const char* name, int32_t priority, size_t stack) {
    Mutex::Autolock _l(mLock);
    if (mRunning) {
        return INVALID_OPERATION;
    }
    mStatus = NO_ERROR;
    mExitPending = false;
    mThread = thread_id_t(-1);
    mHoldSelf = this; // 對自己持有強引用
    mRunning = true;
    bool res;
    if (mCanCallJava) {
        res = createThreadEtc(_threadLoop, this, name, priority, stack, &mThread);
    } else {
        res = androidCreateRawThreadEtc(_threadLoop, this, name, priority, stack, &mThread);
    }
    if (res == false) {
        mStatus = UNKNOWN_ERROR;
        mRunning = false;
        mThread = thread_id_t(-1);
        mHoldSelf.clear();
        return UNKNOWN_ERROR;
    }
    return NO_ERROR;
}

深入源碼會較為複雜,但可以确定的是它呼叫的執行緒函數是 _threadLoop:

int Thread::_threadLoop(void* user) {
    Thread* const self = static_cast<Thread*>(user);
    do {
        bool result;
        if (first) {
            first = false;
            self->mStatus = self->readyToRun(); // 首次呼叫繼承類的 readyToRun
            result = (self->mStatus == NO_ERROR);
        } else {
            result = self->threadLoop(); // 進入執行緒循環
        }
    } while (...);
}

這裡的 self 就是我們新建的物件。首次會呼叫類 A 的 readyToRun(),隨後進入 threadLoop 循環,執行緒的退出主要由 threadLoop 的返回結果決定。

四、運算符重載與多態

當我們寫 mA->fun() 時,看似普通的指標呼叫,實際上 mA 只是一個 sp 類物件,它呼叫的是 sp 重載的 operator->:

inline T& operator* () const { return *m_ptr; }
inline T* operator-> () const { return m_ptr; }
inline T* get() const { return m_ptr; }

由於 m_ptr 指向 new A() 出來的物件,因此最終呼叫的是類 A 的成員函數。賦值運算符也有類似設計:

template<typename T>
sp<T>& sp<T>::operator = (T* other) {
    if (other) other->incStrong(this);
    if (m_ptr) m_ptr->decStrong(this);
    m_ptr = other;
    return *this;
}

這些細節都與 C++ 的多態、重載機制緊密相連。理解這些基礎類,往往能在閱讀 Framework 源碼時事半功倍、心領神會。

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