iOS自动释放池的底层原理

什么是自动释放池

点击参考官方文档;

自动释放池底层原理

常见问题:

1、临时变量什么时候释放?
2、自动释放池的底层结构是什么样的?
3、自动释放池能否嵌套调用?

底层结构
  • 通过源码观察自动释放池的底层结构。自动释放池本身也是一个对象:
struct AutoreleasePoolPageData
{
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
    struct AutoreleasePoolEntry {
        uintptr_t ptr: 48;
        uintptr_t count: 16;

        static const uintptr_t maxCount = 65535; // 2^16 - 1
    };
    static_assert((AutoreleasePoolEntry){ .ptr = MACH_VM_MAX_ADDRESS }.ptr == MACH_VM_MAX_ADDRESS, "MACH_VM_MAX_ADDRESS doesn't fit into AutoreleasePoolEntry::ptr!");
#endif

    magic_t const magic;
    __unsafe_unretained id *next;
    pthread_t const thread;
    AutoreleasePoolPage * const parent;
    AutoreleasePoolPage *child;
    uint32_t const depth;
    uint32_t hiwat;

    AutoreleasePoolPageData(__unsafe_unretained id* _next, pthread_t _thread, AutoreleasePoolPage* _parent, uint32_t _depth, uint32_t _hiwat)
        : magic(), next(_next), thread(_thread),
          parent(_parent), child(nil),
          depth(_depth), hiwat(_hiwat)
    {
    }
};

magic_t const magic; //用来校验AutoreleasePoolPage的结构是否完整
__unsafe_unretained id *next;//指向新添加的autorelease对象的下一个,初始化时指向begin();
pthread_t const thread;//指向当前线程
AutoreleasePoolPage * const parent;//指向父节点,第一个节点的parent为nil;
AutoreleasePoolPage *child;//指向当前子节点,最后一个节点的chil为nil;
uint32_t const depth;//代表深度,从0开始,往后递增1;
uint32_t hiwat;// 代表high water mark最大入栈数量标记

AutoreleasePoolPage继承自AutoreleasePoolPageData。它的结构体如下:

class AutoreleasePoolPage : private AutoreleasePoolPageData
{
    friend struct thread_data_t;

public:
    static size_t const SIZE =
#if PROTECT_AUTORELEASEPOOL
        PAGE_MAX_SIZE;  // must be multiple of vm page size
#else
        PAGE_MIN_SIZE;  // size and alignment, power of 2
#endif
    
private:
    static pthread_key_t const key = AUTORELEASE_POOL_KEY;
    static uint8_t const SCRIBBLE = 0xA3;  // 0xA3A3A3A3 after releasing
    static size_t const COUNT = SIZE / sizeof(id);
    static size_t const MAX_FAULTS = 2;

    // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is 
    // pushed and it has never contained any objects. This saves memory 
    // when the top level (i.e. libdispatch) pushes and pops pools but 
    // never uses them.
#   define EMPTY_POOL_PLACEHOLDER ((id*)1)

#   define POOL_BOUNDARY nil
 id * begin() {
        return (id *) ((uint8_t *)this+sizeof(*this));
    }

    id * end() {
        return (id *) ((uint8_t *)this+SIZE);
    }

    bool empty() {
        return next == begin();
    }

    bool full() { 
        return next == end();
    }

    bool lessThanHalfFull() {
        return (next - begin() < (end() - begin()) / 2);
    }
...
}
  • 关于自动释放池的结构,可以从源码的注释来解读:
 A thread's autorelease pool is a stack of pointers. Each pointer is either an object to release, or POOL_BOUNDARY which is an autorelease pool boundary. A pool token is a pointer to the POOL_BOUNDARY for that pool. When the pool is popped, every object hotter than the sentinel is released. The stack is divided into a doubly-linked list of pages. Pages are added and deleted as necessary. Thread-local storage points to the hot page, where newly autoreleased objects are stored.

翻译过来就是线程的自动释放池是一个指针堆栈。每个指针要么是一个要释放的对象,要么是POOL_BOUNDARY自动释放池边界(也就是哨兵对象)。池的token是指向该池的POOL_BOUNDARY的指针。当池进行pop时,每个比哨兵(POOL_BOUNDARY)活跃(因为是栈,所以后进先出,哨兵对象是栈底位置)的对象都被释放。堆栈被分成一个双链接的页(AutoreleasePoolPage)列表。页面添加并在必要时删除。新自动释放的对象存储存储的页是hotPage,线程局部存储指向hotPage。根据描述,得出如下结构图:


自动释放池.jpg
对象添加push流程

自动释放对象添加进入自动释放池其实就是进行压榨push操作,主要就是在AutoreleasePoolPage::push()方法进行的,其源码如下:

 static inline void *push() 
    {
        id *dest;
        if (slowpath(DebugPoolAllocation)) {
            // Each autorelease pool starts on a new pool page.
            dest = autoreleaseNewPage(POOL_BOUNDARY);
        } else {
            dest = autoreleaseFast(POOL_BOUNDARY);
        }
        ASSERT(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }
 static inline id *autoreleaseFast(id obj)
    {
        AutoreleasePoolPage *page = hotPage();
        if (page && !page->full()) {
            return page->add(obj);
        } else if (page) {
            return autoreleaseFullPage(obj, page);
        } else {
            return autoreleaseNoPage(obj);
        }
    }

正常都会走autoreleaseFast流程,POOL_BOUNDARY是个哨兵对象。autoreleaseFast方法中主要就是先判断有没有已存在的page,没有的话就调用autoreleaseNoPage方法;有的话判断当前page是否已满,已满走autoreleaseFullPage;未满走add。
根据源码总结push操作流程如下:
1、第一次进来,且传入的是POOL_BOUNDARY(哨兵对象) 的时候,会判断当前线程是否已经创建AutoreleasePoolPage,如果没有,就会从当前线程获取一个占位的释放池(autoreleaseFast->autoreleaseNoPage),然后返回哨兵对象地址(这个地址在后面pod方法传回来:

   if (obj == POOL_BOUNDARY  &&  !DebugPoolAllocation) {
            // We are pushing a pool with no pool in place,
            // and alloc-per-pool debugging was not requested.
            // Install and return the empty pool placeholder.
            return setEmptyPoolPlaceholder();
        }
static inline id* setEmptyPoolPlaceholder()
    {
        ASSERT(tls_get_direct(key) == nil);
        tls_set_direct(key, (void *)EMPTY_POOL_PLACEHOLDER);
        return EMPTY_POOL_PLACEHOLDER;
    }
 // EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is 
    // pushed and it has never contained any objects. This saves memory 
    // when the top level (i.e. libdispatch) pushes and pops pools but 
    // never uses them.
#   define EMPTY_POOL_PLACEHOLDER ((id*)1)

2、如果第一进来且传入的不是一个POOL_BOUNDARY,而是真正的对象(比如对象调用autorelease方法),则手动创建一个AutoreleasePoolPage,并且把POOL_BOUNDARY第一个压栈,然后把对象指针压栈,然后返回哨兵对象地址(这个地址在后面pod方法传回来):

  // Install the first page.
        AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
        setHotPage(page);
        
        // Push a boundary on behalf of the previously-placeholder'd pool.
        if (pushExtraBoundary) {
            page->add(POOL_BOUNDARY);
        }
        
        // Push the requested object or pool.
        return page->add(obj);

3、不是第一次进来的话,且当前hotPage还未压满时,直接压榨:

if (page && !page->full()) {
            return page->add(obj);
        }

4、如果当前hotPage已满,则创建新的page,新的page置为之前hotPage的child,hotPage置为新page的perent,然后把新的page设置成hotPage。然后把obj直接压到新的page中,这里不需要像第一个page那样需要哨兵对象,添加对象之后返回next:

    id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
    {
        // The hot page is full. 
        // Step to the next non-full page, adding a new page if necessary.
        // Then add the object to that page.
        ASSERT(page == hotPage());
        ASSERT(page->full()  ||  DebugPoolAllocation);

        do {
            if (page->child) page = page->child;
            else page = new AutoreleasePoolPage(page);
        } while (page->full());

        setHotPage(page);
        return page->add(obj);
    }
对象出战pop流程

pop操作主要在方法AutoreleasePoolPage::pop()中进行的。pop操作流程主要做如下几件事情:
1、容错处理,比如盘空、异常等处理;
2、如果自动释放池正常,会调用popPage方法进行真正的出栈,先是把对象一个个出栈,然后一个个调用release方法(popPage->releaseUntil):

 page->releaseUntil(stop);

    void releaseUntil(id *stop) 
    {
        // Not recursive: we don't want to blow out the stack 
        // if a thread accumulates a stupendous amount of garbage
        
        while (this->next != stop) {
            // Restart from hotPage() every time, in case -release 
            // autoreleased more objects
            AutoreleasePoolPage *page = hotPage();

            // fixme I think this `while` can be `if`, but I can't prove it
            while (page->empty()) {
                page = page->parent;
                setHotPage(page);
            }

            page->unprotect();
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
            AutoreleasePoolEntry* entry = (AutoreleasePoolEntry*) --page->next;

            // create an obj with the zeroed out top byte and release that
            id obj = (id)entry->ptr;
            int count = (int)entry->count;  // grab these before memset
#else
            id obj = *--page->next;
#endif
            memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
            page->protect();

            if (obj != POOL_BOUNDARY) {
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
                // release count+1 times since it is count of the additional
                // autoreleases beyond the first one
                for (int i = 0; i < count + 1; i++) {
                    objc_release(obj);
                }
#else
                objc_release(obj);
#endif
            }
        }

        setHotPage(this);

#if DEBUG
        // we expect any children to be completely empty
        for (AutoreleasePoolPage *page = child; page; page = page->child) {
            ASSERT(page->empty());
        }
#endif
    }

stop指针是自动释放池创建时的栈底地址(哨兵对象地址),由pop(stop)方法调用时返回,这样就可以把stop之后的对象一个个pop出来,然后调用release方法释放引用计数。
4、把各个page的对象释放完之后,就开始清理page链表:

    static void
    popPage(void *token, AutoreleasePoolPage *page, id *stop)
    {
        if (allowDebug && PrintPoolHiwat) printHiwat();

        page->releaseUntil(stop);

        // memory: delete empty children
        if (allowDebug && DebugPoolAllocation  &&  page->empty()) {
            // special case: delete everything during page-per-pool debugging
            AutoreleasePoolPage *parent = page->parent;
            page->kill();
            setHotPage(parent);
        } else if (allowDebug && DebugMissingPools  &&  page->empty()  &&  !page->parent) {
            // special case: delete everything for pop(top)
            // when debugging missing autorelease pools
            page->kill();
            setHotPage(nil);
        } else if (page->child) {
            // hysteresis: keep one empty child if page is more than half full
            if (page->lessThanHalfFull()) {
                page->child->kill();
            }
            else if (page->child->child) {
                page->child->child->kill();
            }
        }
    }

自动释放池创建和销毁时机

在ARC环境下,在主线程中,会默认创建一些Runloop。

  • 默认runloop的创建和销毁时机为:

第一次创建:启动runloop时
最后一次销毁:runloop退出时
其他时候的创建和销毁:当runloop即将进行休眠状态时会销毁旧的释放池,并创建一个新的释放池。

  • 如果是我们手动创建的runloop则是在超过它的作用域的时候销毁。

什么时候需要自动释放池

  • 写给予命令行的程序时,就是没有UI框架;
  • 写循环,循环里边包含了大量临时创建的对象;
  • 创建了新的线程;
  • 长时间在后台运行的任务;
  • 合理运用自动释放池,可以降低程序的内存峰值,异步的方式将文件保存在磁盘(SDWebimage里边异步保存图片到磁盘,类似的占用内存的操作);

你可能感兴趣的:(iOS自动释放池的底层原理)