手把手带你探索AutoreleasePool

2022-12-30  本文已影响0人  会骑车的iOSer

总所周知在MRC时代,经常会用到AutoreleasePool帮助开发者管理内存;但在ARC时,这部分的内存管理操作却被系统所代替了,不再手动的去release或者autorelease等操作了,不过AutoreleasePool仍然在背后发挥着极大的作用,今天我们就从以下几个方面来探索下AutoreleasePool

1.什么是autorelease& autoreleasePool

对象执行 autorelease 方法或者直接在 autoreleasePool 中创建对象,会将对象添加到 autoreleasePool 中,当自动释放池销毁的时候,会对所有对象做 release 操作

@interface MGMan : NSObject

+ (instancetype)object;

@end

@implementation MGMan

- (void)dealloc {
    NSLog(@"MGMan dealloc");
}

//这个方法返回autorelease对象
+ (instancetype)object {
    return [[MGMan alloc] init];
}

@end

- (void)testARCRule {
    __weak id tmp1 = nil;
    __weak id tmp2 = nil;
    {
        MGMan *man1 = [MGMan object];
        MGMan *man2 = [[MGMan alloc] init];
        tmp1 = man1;
        tmp2 = man2;
    }
    NSLog(@"tmp1 = %@", tmp1);
    NSLog(@"tmp2 = %@", tmp2);
}
//打印结果
//MGMan dealloc
//tmp1 = <MGMan: 0x600001188230>
//tmp2 = (null)
//MGMan dealloc

在作用域外,声明了两个弱引用对象tmp1tmp2,在作用域内,分别对tmp1tmp2赋值,并在作用域外分别打印tmp1tmp2,为什么tmp1tmp2的打印结果不一样呢,man1man2的释放时机也不一样

⚠️注意
ARC的规则:alloc/new/copy/mutableCopy 开头的方法返回的对象不是 autorelease 对象


@interface MGMan : NSObject

+ (instancetype)object;

+ (NSString *)newString;
+ (NSString *)allocString;
+ (NSString *)copyString;

+ (NSString *)initString;
+ (NSString *)helloString;
+ (NSString *)createString;
@end

#import "MGMan.h"

@implementation MGMan

- (void)dealloc {
    NSLog(@"MGMan dealloc");
}

//这个方法返回autorelease对象
+ (instancetype)object {
    return [[MGMan alloc] init];
}


+ (NSString *)newString {
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];    
}

+ (NSString *)allocString {
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];
}

+ (NSString *)copyString {
    //帮我们插入autorelease
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];
}

+ (NSString *)initString {
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];
}

+ (NSString *)helloString {
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];
}

+ (NSString *)createString {
    return [[NSString alloc] initWithCString:"Hello Objective-c" encoding:NSUTF8StringEncoding];
}

- (void)testARCRule {    
    @autoreleasepool {
        //Tagged Pointer
        //LLVM 并不会发送autorelease消息
        __weak NSString *tmp1 = [MGMan newString];
        __weak NSString *tmp2 = [MGMan allocString];
        __weak NSString *tmp3 = [MGMan copyString];
        NSLog(@"%@", tmp1);
        NSLog(@"%@", tmp2);
        NSLog(@"%@", tmp3);

        __weak NSString *tmp4 = [MGMan initString];
        __weak NSString *tmp5 = [MGMan helloString];
        __weak NSString *tmp6 = [MGMan createString];
        NSLog(@"%@", tmp4);
        NSLog(@"%@", tmp5);
        NSLog(@"%@", tmp6);
    }
}
//打印结果
//(null)
//(null)
//(null)
//Hello Objective-c
//Hello Objective-c
//Hello Objective-c

上面这个例子验证了ARC的规则:alloc/new/copy/mutableCopy 开头的方法返回的对象不是 autorelease 对象

autoreleasePool的使用

//    1、生成一个NSAutoreleasePool对象
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//    2、调用autorelease方法
    id object = [[NSObject alloc] init];
    [object autorelease];
//    3、对象销毁
    [pool drain];
    
    @autoreleasepool {
        //LLVM
        id object = [[NSObject alloc] init];
    }

在ARC环境下其实是我们的系统自动帮我们调用了autorelease,我们可以结合源码GNUStep来看下

#ifndef AUTORELEASE
/**
 *  Basic autorelease operation ... calls [NSObject-autorelease]<br />
 *  Does nothing when ARC is in use.
 */
#define AUTORELEASE(object) [(id)(object) autorelease]
#endif

+ (id) arrayWithCapacity: (NSUInteger)numItems
{
  return AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()]
    initWithCapacity: numItems]);
}

当我们初始化的时候,系统会自动帮我们调用AUTORELEASE宏定义去包裹

2.autoreleasePool原理解析

新创建一个项目

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
    }
    return 0;
}

我们clang下,看下@autoreleasepool{}具体做了什么

通过clang我们得到以下代码

struct __AtAutoreleasePool {
  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
  void * atautoreleasepoolobj;
};

int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_fc_dm6qr3kj7mbfs5kj1td4_f1c0000gn_T_main_3eea55_mi_0);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

接下来我们来探究下objc_autoreleasePoolPush ()objc_autoreleasePoolPop()方法 源码下载地址
我这里使用的是objc4-866.9

objc_autoreleasePoolPush ()方法

void *
objc_autoreleasePoolPush(void)
{
    return AutoreleasePoolPage::push();
}

返回AutoreleasePoolPage,并且调用了push()函数

首先来看下AutoreleasePoolPage

class AutoreleasePoolPage : private AutoreleasePoolPageData

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 = OBJC_VM_MAX_ADDRESS }.ptr == OBJC_VM_MAX_ADDRESS, "OBJC_VM_MAX_ADDRESS doesn't fit into AutoreleasePoolEntry::ptr!");
#endif

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

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

接着我们再来看下push()方法

    static inline void *push() 
    {
        ReturnAutoreleaseInfo info = getReturnAutoreleaseInfo();
        moveTLSAutoreleaseToPool(info);

        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 == (id *)EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }

接着我们再来看下autoreleaseFast()方法

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

接着我们再来看下hotPage()方法

static tls_direct(AutoreleasePoolPage *, tls_key::autorelease_pool, HotPageDealloc)
        hotPage_;

static inline AutoreleasePoolPage *hotPage() 
    {
        AutoreleasePoolPage *result = hotPage_;
        if (result == EMPTY_POOL_PLACEHOLDER) return nil;
        if (result) result->fastcheck();
        return result;
    }

从上面的代码中我们不难发现,

然后我们来看下page->add(obj)是怎么把obj插入到链表中去的

id *add(id obj)
    {
        ASSERT(!full());
        unprotect();
        id *ret;

#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
        if (!DisableAutoreleaseCoalescing || !DisableAutoreleaseCoalescingLRU) {
            if (!DisableAutoreleaseCoalescingLRU) {
                if (!empty() && (obj != POOL_BOUNDARY)) {
                    AutoreleasePoolEntry *topEntry = (AutoreleasePoolEntry *)next - 1;
                    for (uintptr_t offset = 0; offset < 4; offset++) {
                        AutoreleasePoolEntry *offsetEntry = topEntry - offset;
                        if (offsetEntry <= (AutoreleasePoolEntry*)begin() || *(id *)offsetEntry == POOL_BOUNDARY) {
                            break;
                        }
                        if (offsetEntry->ptr == (uintptr_t)obj && offsetEntry->count < AutoreleasePoolEntry::maxCount) {
                            if (offset > 0) {
                                AutoreleasePoolEntry found = *offsetEntry;
                                memmove(offsetEntry, offsetEntry + 1, offset * sizeof(*offsetEntry));
                                *topEntry = found;
                            }
                            topEntry->count++;
                            ret = (id *)topEntry;  // need to reset ret
                            goto done;
                        }
                    }
                }
            } else {
                if (!empty() && (obj != POOL_BOUNDARY)) {
                    AutoreleasePoolEntry *prevEntry = (AutoreleasePoolEntry *)next - 1;
                    if (prevEntry->ptr == (uintptr_t)obj && prevEntry->count < AutoreleasePoolEntry::maxCount) {
                        prevEntry->count++;
                        ret = (id *)prevEntry;  // need to reset ret
                        goto done;
                    }
                }
            }
        }
#endif
        ret = next;  // faster than `return next-1` because of aliasing
        *next++ = obj;
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
        // Make sure obj fits in the bits available for it
        ASSERT(((AutoreleasePoolEntry *)ret)->ptr == (uintptr_t)obj);
#endif
     done:
        protect();
        return ret;
    }

如图所示链表有一个起始位置begin(),begin()指向的位置为整个存储的空间减去page数据结构的空间,同时也有一个结束位置end(), end则是this指针加上整个链表的长度,当前有个指针叫next,next指针指向的是当前空地址的首地址,如果当前链表是空的,那么next指针指向的是begin()位置,当前如果向链表中插入一个对象obj,那么此时next指针则会*next++ = obj;指向下一个地址,同时插入obj之前会存放一个POOL_BOUNDARY(哨兵对象),并且返回retnext上一个指向的位置,如果链表存满后,则会重新声明新的链表继续存放对象,每张链表的容积为2的14次方(16384)字节(以前老版本为4096)

objc_autoreleasePoolPop ()方法

NEVER_INLINE
void
objc_autoreleasePoolPop(void *ctxt)
{
    AutoreleasePoolPage::pop(ctxt);
}

在前文的__AtAutoreleasePool结构体中我们得到,构造函数会调用objc_autoreleasePoolPush并返回atautoreleasepoolobj,这个atautoreleasepoolobj其实就是POOL_BOUNDARY的地址,当调用objc_autoreleasePoolPop又会把POOL_BOUNDARY地址传进去

static inline void
    pop(void *token)
    {
        // We may have an object in the ReturnAutorelease TLS when the pool is
        // otherwise empty. Release that first before checking for an empty pool
        // so we don't return prematurely. Loop in case the release placed a new
        // object in the TLS.
        while (releaseReturnAutoreleaseTLS())
            ;

        AutoreleasePoolPage *page;
        id *stop;
        if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
            // Popping the top-level placeholder pool.
            page = hotPage();
            if (!page) {
                // Pool was never used. Clear the placeholder.
                return setHotPage(nil);
            }
            // Pool was used. Pop its contents normally.
            // Pool pages remain allocated for re-use as usual.
            page = coldPage();
            token = page->begin();
        } else {
            page = pageForPointer(token);
        }

        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 (slowpath(PrintPoolHiwat || DebugPoolAllocation || DebugMissingPools)) {
            return popPageDebug(token, page, stop);
        }

        return popPage<false>(token, page, stop);
    }
template<bool allowDebug>
    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();
            }
        }
    }

通过调用page->releaseUntil(stop);对当前链表里的对象进行release操作

void releaseUntil(id *stop) 
    {
        // Not recursive: we don't want to blow out the stack 
        // if a thread accumulates a stupendous amount of garbage

        do {
            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
                }
            }

            // Stale return autorelease info is conceptually autoreleased. If
            // there is any, release the object in the info. If stale info is
            // present, we have to loop in case it autoreleased more objects
            // when it was released.
        } while (releaseReturnAutoreleaseTLS());

        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)viewDidLoad {
    [super viewDidLoad];
  
    @autoreleasepool {
        MGMan *man1 = [[MGMan alloc] init];
        @autoreleasepool {
            MGMan *man2 = [[MGMan alloc] init];
            @autoreleasepool {
                MGMan *man3 = [[MGMan alloc] init];
            };
        };
    };
}

⚠️注意
@autoreleasepool{}嵌套使用不一定会创建新的释放池,创建新的释放池唯一标准,当前是否有释放池并且当前释放池是否已经存满

3.线程,Runloop以及autoreleasePool

通过一下示例观察线程与AutoreleasePool关系

__weak id tmp = nil;

/**
线程和 AutoreleasePool
 */
- (void)test_one {
    
    [NSThread detachNewThreadSelector:@selector(testAction) toTarget:self withObject:nil];
}

- (void)testAction {
    
    __autoreleasing id test = [NSObject new];
    NSLog(@"obj=%@", test);
    tmp = test;
    
    [[NSThread currentThread] setName:@"test runloop thread"];
    NSLog(@"thread ending");
}

首先我们添加一个断点[NSThread exit]查看线程何时退出

我们观察下tmp 值的变化


tmp的值发生变化,同时也打印了thread ending说明任务已经执行完成,[NSThread exit]断点也触发了

线程退出后tmp也被释放了

这也正好契合我们开始的观点

上一篇 下一篇

猜你喜欢

热点阅读