iOS 自动释放池autoreleasepool(二)

上一篇文章介绍了autoreleasepool的AutoreleasepoolPage,这篇文章我们就来主要讲讲AutoreleasepoolPage::PushAutoreleasepoolPage::Pop 还有一个autorelease

AutoreleasepoolPage::Push

static inline void *push() 
    {
        id *dest;
        if (DebugPoolAllocation) {
            // Each autorelease pool starts on a new pool page.
            // 每个autoreleasepool从一个新的page开始
            dest = autoreleaseNewPage(POOL_BOUNDARY);
        } else {
            // 已经有线程的页
            dest = autoreleaseFast(POOL_BOUNDARY);
        }
        assert(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }

这里分开两条路,我们先看第一个

autoreleaseNewPage

先说一下大概流程

1.获取一个活跃的页
2.判断这页是不是满了,满的就新建一个page
3.如果没获取到page,也是新建一个页
4.把要push的obj,push到对应的页里

1、
   id *autoreleaseNewPage(id obj)
    {
        //获取一个活跃的页
        AutoreleasePoolPage *page = hotPage();
        //如果有就返回,并且判断是否是满的,满的就会新建一个page
        if (page) return autoreleaseFullPage(obj, page);
        //如果没获取到page
        else return autoreleaseNoPage(obj);
    }
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
2、
    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);

        // 如果满了就循环,这一页有child的话 就指向child,再继续判断是否满
        // 直到没有child 就创建一个新的页
        do {
            if (page->child) page = page->child;
            else page = new AutoreleasePoolPage(page);
        } while (page->full());
        // 设置成活跃的页
        setHotPage(page);
        // 将Obj 添加到这页里
        return page->add(obj);
    }
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
3、
    id *autoreleaseNoPage(id obj)
    {
        // "No page" could mean no pool has been pushed
        // or an empty placeholder pool has been pushed and has no contents yet
        assert(!hotPage());

        // 翻译:pushExtraBoundary 推入一个额外边界
        bool pushExtraBoundary = false;
        if (haveEmptyPoolPlaceholder()) {
            // We are pushing a second pool over the empty placeholder pool
            // or pushing the first object into the empty placeholder pool.
            // Before doing that, push a pool boundary on behalf of the pool 
            // that is currently represented by the empty placeholder.
            //当push一个新页或者第一页的时候,在push之前需要先push一个poolboundary(边界)
            pushExtraBoundary = true;
        }
        else if (obj != POOL_BOUNDARY  &&  DebugMissingPools) {
            // We are pushing an object with no pool in place, 
            // and no-pool debugging was requested by environment.
            _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
                         "autoreleased with no pool in place - "
                         "just leaking - break on "
                         "objc_autoreleaseNoPool() to debug", 
                         pthread_self(), (void*)obj, object_getClassName(obj));
            objc_autoreleaseNoPool(obj);
            return nil;
        }
        else 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();
        }

        // We are pushing an object or a non-placeholder'd pool.

        // 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);
    }

到此,第一条路就走完了。

autoreleaseFast
1、
    static inline id *autoreleaseFast(id obj)
    {
        //同样获取一个活页
        AutoreleasePoolPage *page = hotPage();
        if (page && !page->full()) {//如果page没满的话
            return page->add(obj);
        } else if (page) {//如果page满了
            return autoreleaseFullPage(obj, page);
        } else {//没有获取到活页
            return autoreleaseNoPage(obj);
        }
    }
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
2、
    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);

        // 如果满了就循环,这一页有child的话 就指向child,再继续判断是否满
        // 直到没有child 就创建一个新的页
        do {
            if (page->child) page = page->child;
            else page = new AutoreleasePoolPage(page);
        } while (page->full());
        // 设置成活跃的页
        setHotPage(page);
        // 将Obj 添加到这页里
        return page->add(obj);
    }
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
3、 
    id *autoreleaseNoPage(id obj)
    {
        // "No page" could mean no pool has been pushed
        // or an empty placeholder pool has been pushed and has no contents yet
        assert(!hotPage());

        // 翻译:pushExtraBoundary 推入一个额外边界
        bool pushExtraBoundary = false;
        if (haveEmptyPoolPlaceholder()) {
            // We are pushing a second pool over the empty placeholder pool
            // or pushing the first object into the empty placeholder pool.
            // Before doing that, push a pool boundary on behalf of the pool 
            // that is currently represented by the empty placeholder.
            //当push一个新页或者第一页的时候,在push之前需要先push一个poolboundary(边界)
            pushExtraBoundary = true;
        }
        else if (obj != POOL_BOUNDARY  &&  DebugMissingPools) {
            // We are pushing an object with no pool in place, 
            // and no-pool debugging was requested by environment.
            _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
                         "autoreleased with no pool in place - "
                         "just leaking - break on "
                         "objc_autoreleaseNoPool() to debug", 
                         pthread_self(), (void*)obj, object_getClassName(obj));
            objc_autoreleaseNoPool(obj);
            return nil;
        }
        else 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();
        }

        // We are pushing an object or a non-placeholder'd pool.

        // 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);
    }

其实这两条路是差不多的,在底层中都走了这两个的方法
autoreleaseFullPage
autoreleaseNoPage
感觉完全可以合起来啊- -,不知道苹果这么处理是为了什么。

page->add()

push的最终操作也就是这个add,看看这里都干了什么

    id *add(id obj)
    {
        assert(!full());
        unprotect(); //取消保护
        id *ret = next;  // faster than `return next-1` because of aliasing
        *next++ = obj;
        protect(); // 保护
        return ret;
    }

这里做了什么呢

  1. 这里面有unprotect() protect() 这两个可以理解为加锁类似NSLock
  2. 创建一个临时变量ret 来存储next
  3. next ++ 内存地址移动。类似 0x0001 -> 0x0002
  4. 将obj存储到新移动出来的内存地址上

那么push就先到这里,接下来说说autorelease

autorelease

在了解过push之后,我们可以很容易理解这个autorelease。看下面的代码跳转,
autorelease最终走到了一个上文出现过的方法autoreleaseFast(),那么其实autorelease做的操作也跟push一样

- (id)autorelease {
    return ((id)self)->rootAutorelease();
}
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
objc_object::rootAutorelease()
{
    if (isTaggedPointer()) return (id)this;
    if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;

    return rootAutorelease2();
}
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
objc_object::rootAutorelease2()
{
    assert(!isTaggedPointer());
    return AutoreleasePoolPage::autorelease((id)this);
}
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
static inline id autorelease(id obj)
{
    assert(obj);
    assert(!obj->isTaggedPointer());
    id *dest __unused = autoreleaseFast(obj);
    assert(!dest  ||  dest == EMPTY_POOL_PLACEHOLDER  ||  *dest == obj);
        return obj;
}

AutoreleasepoolPage::Pop

先简单说一下都做了什么

  1. 判断当前pop对象是否是空池占位符,是的话就推出去,按道理一般很少进去
  2. 通过栈顶的地址找到对应的page
  3. 记录最高水位标记
  4. 开始pop,objc_release(obj);
  5. kill空白页
    static inline void pop(void *token) 
    {
        AutoreleasePoolPage *page;
        id *stop;
        //只有在push的时候 push了一个边界符, 才有可能出现EMPTY_POOL_PLACEHOLDER
        if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
            // Popping the top-level placeholder pool.
            // 推出最顶上的占位池
            if (hotPage()) {
                // Pool was used. Pop its contents normally.
                // Pool pages remain allocated for re-use as usual.
                // 递归 coldPage调用begin
                pop(coldPage()->begin());
            } else {
                // Pool was never used. Clear the placeholder.
                setHotPage(nil);
            }
            return;
        }

        // 通过栈顶的地址找到对应的page
        page = pageForPointer(token);
        //token赋值给stop
        stop = (id *)token;
        if (*stop != POOL_BOUNDARY) {
            if (stop == page->begin()  &&  !page->parent) {
                // Start of coldest page may correctly not be POOL_BOUNDARY:
                // 1. top-level pool is popped, leaving the cold page in place
                // 2. an object is autoreleased with no pool
            } else {
                // Error. For bincompat purposes this is not 
                // fatal in executables built with old SDKs.
                return badPop(token);
            }
        }

        // 记录最高水位标记
        if (PrintPoolHiwat) printHiwat();
        // 从栈顶开始操作出栈,并向栈中的对象发送release消息,直到遇到第一个边界符
        page->releaseUntil(stop);

        // memory: delete empty children
        // 删除空的child页
        if (DebugPoolAllocation  &&  page->empty()) {
            // special case: delete everything during page-per-pool debugging
            AutoreleasePoolPage *parent = page->parent;
            page->kill();
            setHotPage(parent);
        } else if (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();
            }
        }
    }

---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
    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);
            }

            //类似push时候的操作
            page->unprotect();
            id obj = *--page->next;
            memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
            page->protect();

            if (obj != POOL_BOUNDARY) {
                //如果当前对象不是边界符,就释放对象
                objc_release(obj);
            }
        }

        setHotPage(this);

#if DEBUG
        // we expect any children to be completely empty
        for (AutoreleasePoolPage *page = child; page; page = page->child) {
            assert(page->empty());
        }
#endif
    }
---------------------------------------- 华丽的分割线 ---------------------------------------------------------------------
    void kill() 
    {
        // Not recursive: we don't want to blow out the stack 
        // if a thread accumulates a stupendous amount of garbage
        AutoreleasePoolPage *page = this;
        //如果page有child节点 就不断循环直到不再有child
        while (page->child) page = page->child;

        //创建一个deathptr临时变量来存储page
        AutoreleasePoolPage *deathptr;
        //如果page不等于this(可以理解成self)
        //就不断的循环把child节点一层一层的置为nil
        do {
            deathptr = page;
            page = page->parent;
            if (page) {
                page->unprotect();
                page->child = nil;
                page->protect();
            }
            delete deathptr;
        } while (deathptr != this);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,014评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,796评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,484评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,830评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,946评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,114评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,182评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,927评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,369评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,678评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,832评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,533评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,166评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,885评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,128评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,659评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,738评论 2 351