Android 强弱指针分析

Android 强弱指针分析

在C C++ 语言中,内存的管理历来是一个比较难的问题,在java 中内存new 的对象由jvm 虚拟机自动回收。在Android 上面提供了sp 和wp 两种类型的指针,管理new 出来的对象,能够自动的回收对象,减轻在内存管理上的负担。

实现对对象的管理通常的做法是使用引用计数,每增加一次引用引用计数增加一,当引用计数为0时,销毁这个对象。引用计数可以放在对象内部,也可以放在外部。Android的做法是放在对象内部。

在Android 7.0 版本上相关的代码及位置在:

  • system/core/libutils/RefBase.cpp
  • system/core/include/utils/RefBase.h
  • system/core/include/utils/StrongPointer.h

C++ 11

在C++ 11 中引入了大量的新特性,使一些开发变得简单。在引用计数的变量上使用了
std::atomic模板类:template struct atomic;提供原子操作,在原来的版本上使用的是Android平台封装的API。
主要用到两个API:fetch_add 和fetch_sub,用于加1和减1。

integral fetch_add(integral, memory_order = memory_order_seq_cst) volatile;
integral fetch_add(integral, memory_order = memory_order_seq_cst);
integral fetch_sub(integral, memory_order = memory_order_seq_cst) volatile;
integral fetch_sub(integral, memory_order = memory_order_seq_cst);

用于线程的同步的API,没有找到具体的资料。

atomic_thread_fence

参考C++11 并发指南六(atomic 类型详解三 std::atomic (续))

这两个API的最后一个参数是std::memory_order类型。主要是内存模型参数,可以调整代码的执行顺序,告诉编译器的优化方法,比如如果GCC 加了O2参数,会对代码的执行顺序做一定的调整,但是在多线程中就会带来一定的影响,出现错误,内存模型参数可以指定编译器的优化方式,限定多个原子语句的执行顺序。

C++11 并发指南七(C++11 内存模型一:介绍)

/*
std::memory_order
C++  Atomic operations library 
Defined in header <atomic>
*/
enum memory_order {
    memory_order_relaxed,
    memory_order_consume,
    memory_order_acquire,
    memory_order_release,
    memory_order_acq_rel,
    memory_order_seq_cst
};

主要用到两个:

  1. std::memory_order_relaxed:线程内顺序执行,线程间随意。
  2. std::memory_order_seq_cst:多线程保持顺序一致性,像单线程一样的执行。

参考:
std::memory_order

这段内容据说完全搞懂的全球屈指可数。

主要的类

1. RefBase

需要能够自动管理内存的对象都要继承这个类,在RefBase内部有int 型的引用计数。实际是通过weakref_impl类型的mRefs管理。

RefBase::RefBase() : mRefs(new weakref_impl(this))
{
}
void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);
    
    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
   
    if (c != INITIAL_STRONG_VALUE)  {
        return;
    }

    int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
            std::memory_order_relaxed);

    refs->mBase->onFirstRef();
}

void RefBase::decStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);
    const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);

    if (c == 1) {
        std::atomic_thread_fence(std::memory_order_acquire);
        refs->mBase->onLastStrongRef(id);
        int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
        if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            delete this;
            // Since mStrong had been incremented, the destructor did not
            // delete refs.
        }
    }

    refs->decWeak(id);
}

通过 void incStrong(const void* id) const 函数增加引用计数,

  1. refs->incWeak(id); 增加弱引用计数。
  2. 增加强引用计数,如果 const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    返回值c 为初始值INITIAL_STRONG_VALUE,执行onFirstRef。onFirstRef 函数体为空,可以重载做一些初始化工作。

通过 void decStrong(const void* id) const 减少引用计数。

  1. 减少强引用计数 const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
  2. 如果从c==1, 先做一些清理工作:onLastStrongRef 接着删除 delete this
  3. 如果不为1,refs->decWeak(id);

2. RefBase::weakref_type

RefBase::weakref_type 主要定义了两个函数:incWeak, decWeak,操作弱引用计数。

void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c __unused = impl->mWeak.fetch_add(1,std::memory_order_relaxed);
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", 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 = impl->mWeak.fetch_sub(1, std::memory_order_release);
    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
    if (c != 1) return;
    atomic_thread_fence(std::memory_order_acquire);

    int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
    if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
        // This is the regular lifetime case. The object is destroyed
        // when the last strong reference goes away. Since weakref_impl
        // outlive the object, it is not destroyed in the dtor, and
        // we'll have to do it here.
        if (impl->mStrong.load(std::memory_order_relaxed)
                == INITIAL_STRONG_VALUE) {
            // Special case: we never had a strong reference, so we need to
            // destroy the object now.
            delete impl->mBase;
        } else {
            // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
            delete impl;
        }
    } else {
        // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
        // is gone, we can destroy the object.
        impl->mBase->onLastWeakRef(id);
        delete impl->mBase;
    }
}

需要注意的是在执行delete 是使用了mFlags 这个变量,在下边可以看到这个变量的定义。

3. RefBase::weakref_impl

RefBase::weakref_impl 继承自RefBase::weakref_type 真实的引用计数使用RefBase的内部类RefBase::weakref_impl管理, 有四个内部变量:mStong mWeak mBase, mFlags. mStrong 和sp 配合,负责强引用计数;mWeak 和wp 配合,负责弱引用计数。

class RefBase::weakref_impl : public RefBase::weakref_type
{
public:
    std::atomic<int32_t>    mStrong;
    std::atomic<int32_t>    mWeak;
    RefBase* const          mBase;
    std::atomic<int32_t>    mFlags;
}

// mFlags定义
// OBJECT_LIFETIME_STRONG 为默认值,对象以强引用计数管理生命周期
// OBJECT_LIFETIME_WEAK             对象以弱引用计数管理生命周期 

    enum {
        OBJECT_LIFETIME_STRONG  = 0x0000,  
        OBJECT_LIFETIME_WEAK    = 0x0001,
        OBJECT_LIFETIME_MASK    = 0x0001
    };

4. sp 为强指针

负责强引用计数管理,内部有m_ptr 指针保存RefBase对象,重载了 “=”操作符,调用m_ptr的incStrong操作引用计数+1, 析构的时候调用decStrong -1.

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

template<typename T>
sp<T>::~sp() {
    if (m_ptr)
        m_ptr->decStrong(this);
}

5. wp 是弱指针

负责对象之间的解引用。如果子类保存有父指针,父类保存有子指针,在析构的时候子类先析构,但是父类保有子类的引用,导致引用计数不为0,无法删除子类;然后父类析构,子类保有父类的引用计数,父类也无法删除,这时候需要使用wp避免出现这种情况。和sp 一样 wp重载了 操作符“=” 调用 incWeak, 在析构的时候 decWeak。
在RefBase 里面有两个变量mStrong, mWeak 分别保存强弱引用计数,只要强引用计数为0,强制delete。

举个例子:
我们定义两个类A B, 后析构的B使用wp类型的指针保存A,在析构的时候如果弱引用类型不为0,只要强引用类型为0,强制delete。A先析构,强引用类型为0,软引用类型为1,强制delete, 这样B的强引用类型也变为1,B析构的时候执行完del 后强引用类型为0,delete

template<typename T>
wp<T>& wp<T>::operator = (const wp<T>& other)
{
    weakref_type* otherRefs(other.m_refs);
    T* otherPtr(other.m_ptr);
    if (otherPtr) otherRefs->incWeak(this);
    if (m_ptr) m_refs->decWeak(this);
    m_ptr = otherPtr;
    m_refs = otherRefs;
    return *this;
}

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

6. 强弱指针的对比

  1. 通过类图可以发现,强指针实现了 “.” “->” 操作符的重载,因此sp 可以直接方位类成员,而wp 却不能,
  2. 但是wp 可以转化为sp
template<typename T>
sp<T> wp<T>::promote() const
{
    sp<T> result;
    if (m_ptr && m_refs->attemptIncStrong(&result)) {
        result.set_pointer(m_ptr);
    }
    return result;
}

具体的类图如下:
Android 指针类图

二 移植到PC

为了编译研究测试代码,把这是三个文件移植到PC环境下。Andrioid7.0代码针对C++ 11 做了修改,在API的跨平台编译上做的非常好,没什么大的改动,注释掉部分Android的Log 代码就编译通过了。在这里也赞一下 C++ 11。平台为MAC,IDE为CLion 2016.3,编译使用CMake。

coded地址

三 LightRefBase

在不考虑类互相引用的情况下,引用计数比较简单,Android提供了LightRefBase模板类
内部采用 mutable std::atomic<int32_t> mCount; 保存引用计数。

template <class T>
class LightRefBase
{
public:
    inline LightRefBase() : mCount(0) { }
    inline void incStrong(__attribute__((unused)) const void* id) const {
        mCount.fetch_add(1, std::memory_order_relaxed);
    }
    inline void decStrong(__attribute__((unused)) const void* id) const {
        if (mCount.fetch_sub(1, std::memory_order_release) == 1) {
            std::atomic_thread_fence(std::memory_order_acquire);
            delete static_cast<const T*>(this);
        }
    }
    //! DEBUGGING ONLY: Get current strong ref count.
    inline int32_t getStrongCount() const {
        return mCount.load(std::memory_order_relaxed);
    }

    typedef LightRefBase<T> basetype;

protected:
    inline ~LightRefBase() { }

private:
    friend class ReferenceMover;
    inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { }
    inline static void renameRefId(T* ref,
            const void* old_id, const void* new_id) { }

private:
    mutable std::atomic<int32_t> mCount;
};

最开始的测试代码如下:

class LightRefBaseTest: public LightRefBase<LightRefBaseTest>{
public:
    LightRefBaseTest(){std::cout << "Hello, LightRefBaseTest!" << std::endl;};
    ~LightRefBaseTest(){std::cout << "Hello, ~LightRefBaseTest()!" << std::endl;};
};


int main() {
    std::cout << "Hello, World!" << std::endl;
    LightRefBaseTest lightTest;
    return 0;
}

/*
结果:

Hello, World!
Hello, LightRefBaseTest!
Hello, ~LightRefBaseTest()!

Process finished with exit code 0
*/

修改下LightRefBaseTest lightTest 为:

int main() {
    std::cout << "Hello, World!" << std::endl;
    LightRefBaseTest* lightTest = new LightRefBaseTest();
    return 0;
}

/*
结果 LightRefBaseTest没有析构:

Hello, World!
Hello, LightRefBaseTest!

Process finished with exit code 0
*/

再修改下,使用sp 指针,LightRefBaseTest又析构了:

int main() {
    std::cout << "Hello, World!" << std::endl;
    sp<LightRefBaseTest> sp1 = new LightRefBaseTest();
    return 0;
}

/*
看下结果,LightRefBaseTest析构了:

Hello, World!
Hello, LightRefBaseTest!
Hello, ~LightRefBaseTest()!

Process finished with exit code 0
*/

看下互相引用的情况:

class LightRefBaseTest2;

class LightRefBaseTest: public LightRefBase<LightRefBaseTest>{
public:
    LightRefBaseTest(){std::cout << "Hello, LightRefBaseTest!" << std::endl;};
    ~LightRefBaseTest(){std::cout << "Hello, ~LightRefBaseTest()!" << std::endl;};
    void setPointer(sp<LightRefBaseTest2> pointer){mPointer = pointer;};
private:
    sp<LightRefBaseTest2>  mPointer;
};


class LightRefBaseTest2: public LightRefBase<LightRefBaseTest>{
public:
    LightRefBaseTest2(){std::cout << "Hello, LightRefBaseTest2!" << std::endl;};
    ~LightRefBaseTest2(){std::cout << "Hello, ~LightRefBaseTest2()!" << std::endl;};
    void setPointer(sp<LightRefBaseTest> pointer){mPointer = pointer;};

private:
    sp<LightRefBaseTest>  mPointer;
};

int main() {
    std::cout << "Hello, World!" << std::endl;
//    LightRefBaseTest* lightTest = new LightRefBaseTest();
    sp<LightRefBaseTest> sp1 = new LightRefBaseTest();
    sp<LightRefBaseTest2> sp2 = new LightRefBaseTest2();
    sp1->setPointer(sp2);
    sp2->setPointer(sp1);

    return 0;
}
/* 两个类都没有析构。LightRefBaseTest析构的时候由于LightRefBaseTest2持有它的引用,导致不能够调用delete, 同理LightRefBaseTest2也不能够析构
Hello, World!
Hello, LightRefBaseTest!
Hello, LightRefBaseTest2!

Process finished with exit code 0
*/

LightRefBase 已经很完美的解决了C++ new 对象的管理问题,但是有一个致命的缺陷,不能解决类之间的相互引用。

__attribute__

在LightRefBase 的 incStong 和decStrong 的定义中有使用到了__attribute__ 关键字。attribute 关键字为GCC 编译器特有的特性,和平台无关,可以定义函数 变量的属性。

Using GNU C attribute

wp sp RefBase 配合使用 释放内存

image

在下边的讨论中mFlages = OBJECT_LIFETIME_STRONG 为默认值,其他两种情况不讨论。

第一种析构: 析构路线图如图中 A线

这种情况下,强弱引用计数大小一致,在强引用计数首先为0 后,就会引发RefBase 的析构。

class SubRefBaseTest;
class RefBaseTest: public RefBase{
public:
    RefBaseTest(){std::cout << "Hello, RefBaseTest!" << std::endl;};
    ~RefBaseTest(){std::cout << "Hello, ~RefBaseTest()!" << std::endl;};
    void setPointer(sp<SubRefBaseTest> pointer){
        mPointer = pointer;
    };

private:
    sp<SubRefBaseTest> mPointer;
};

class SubRefBaseTest: public RefBase{
public:
    SubRefBaseTest(){ std::cout << "Hello, SubRefBaseTest!" << std::endl;};
    ~SubRefBaseTest(){std::cout << "Hello, ~SubRefBaseTest()!" << std::endl;};
    void setPointer(sp<RefBaseTest> pointer){
        mPointer = pointer;
    };
private:
    sp<RefBaseTest> mPointer;
};

int main() {
    std::cout << "Hello, World!" << std::endl;
    sp<RefBaseTest>  refBaseTest = new RefBaseTest();
    sp<SubRefBaseTest>  subRefBaseTest = new SubRefBaseTest();

    return 0;
}

/*
Hello, World!
Hello, RefBaseTest!
Hello, SubRefBaseTest!
Hello, ~SubRefBaseTest()!
Hello, ~RefBaseTest()!

Process finished with exit code 0
*/
int main() {
    std::cout << "Hello, World!" << std::endl;
    sp<RefBaseTest>  refBaseTest = new RefBaseTest();
    sp<SubRefBaseTest>  subRefBaseTest = new SubRefBaseTest();
    refBaseTest->setPointer(subRefBaseTest);
    subRefBaseTest->setPointer(refBaseTest);
    
    return 0;
}

/* 还是无法析构
Hello, World!
Hello, RefBaseTest!
Hello, SubRefBaseTest!

Process finished with exit code 0
*/
class RefBaseTest: public RefBase{
public:
    RefBaseTest(){std::cout << "Hello, RefBaseTest!" << std::endl;};
    ~RefBaseTest(){std::cout << "Hello, ~RefBaseTest()!" << std::endl;};
    void setPointer(wp<SubRefBaseTest> pointer){
        mPointer = pointer;
    };

private:
    wp<SubRefBaseTest> mPointer;
};

/* 
修改RefBaseTest 引用类型为wp, 正常析构了。
在这里用一个隐式的类型转化,refBaseTest->setPointer(subRefBaseTest);
将强指针转为弱指针。看下重载的 “=” 操作符 弱引用加一。 
Hello, World!
Hello, RefBaseTest!
Hello, SubRefBaseTest!
Hello, ~SubRefBaseTest()!
Hello, ~RefBaseTest()!

Process finished with exit code 0
*/

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

第二种析构

如图中线路B所示,这种情况就是发生了相互引用。先析构的被用弱指针保存。

int main() {
    std::cout << "Hello, World!" << std::endl;

    wp<RefBaseTest> wp1 = new RefBaseTest();
    return 0;
}

~RefBase

new 的对象的处理在这里真正的删除。

  1. 是否有过强引用,没有 删除内部的引用计数对象mRefs,这种情况是OBJECT_LIFETIME_STRONG起作用
  2. OBJECT_LIFETIME_STRONG 不起作用的情况,弱引用计数控制对象生命周期。
  3. 总之,RefBase 的析构中处理引用计数的回收。
RefBase::~RefBase()
{
    if (mRefs->mStrong.load(std::memory_order_relaxed)
            == INITIAL_STRONG_VALUE) {
        // we never acquired a strong (and/or weak) reference on this object.
        delete mRefs;
    } else {
        // life-time of this object is extended to WEAK, in
        // which case weakref_impl doesn't out-live the object and we
        // can free it now.
        int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
        if ((flags & OBJECT_LIFETIME_MASK) != OBJECT_LIFETIME_STRONG) {
            // It's possible that the weak count is not 0 if the object
            // re-acquired a weak reference in its destructor
            if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
                delete mRefs;
            }
        }
    }
    // for debugging purposes, clear this.
    const_cast<weakref_impl*&>(mRefs) = NULL;
}

C++ 11 的智能指针

C++ 智能指针

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值