基于RunLoop进行线程保活的简单分析

线程与RunLoop

线程一般一次只能执行一个任务,执行完成后线程就会退出;如果需要一个执行任务后不退出的永驻线程,可以利用RunLoop实现;
利用RunLoop实现线程保活(常驻线程),我们需要明确线程与RunLoop的关系:

  • 线程和 RunLoop 之间是一一对应的,其关系是保存在一个全局的Dictionary里(key是线程地址, value是RunLoop对象);
  • 线程刚创建时并没有RunLoop,如果不主动获取,那它一直都不会有(主线程的RunLoop在程序启动时系统就已经获取,无需再主动获取);RunLoop的创建是发生在第一次获取时,RunLoop的销毁是发生在线程结束时;
  • 线程添加了RunLoop,并运行起来;实际上是添加了一个do,while循环,这样这个线程的程序一直卡在这个do,while循环上,这样相当于线程的任务一直没有执行完,所以线程一直不会退出;

AFNetworking2.x中的实现

基于RunLoop的线程保活,早期的AFN就有经典的实现:

+ (void)networkRequestThreadEntryPoint:(id)__unused object {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"AFNetworking"];

        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

方法调用:

+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });

    return _networkRequestThread;
}

_networkRequestThread就是创建的常驻线程,这个线程里获取了RunLoop并运行了;所以这个线程不会被退出、销毁,除非RunLoop停止;这样就实现了线程保活功能;

AFNetworking2.x线程保活的作用

  • AFNetworking2.x网络请求是基于NSURLConnection实现的;NSURLConnection是被设计成异步发送的,调用了-start方法后,NSURLConnection 会新建一些线程用底层的CFSocket去发送和接收请求,在发送和接收的一些事件发生后通知原来线程的RunLoop去回调事件。也就是说NSURLConnection的代理回调,也是通过RunLoop触发的;
  • 平常我们自己使用NSURLConnection实现网络请求时,URLConnection的创建与回调一般都是在主线程,主线程本来一直存在所有回调没有问题;
  • AFN作为网络层框架,在NSURLConnection回调回来之后,对Response 做了一些诸如序列化、错误处理的操作的,这些操作都放在子线程去做,处理后接着回到主线程,再通过AFN自己的代理回调给用户;
    AFN的接收NSURLConnection回调的这个线程,正常情况下在执行[connection start]发送网络请求后就立即退出了,后续的回调就调用不了;而线程保活就能确保该线程不退出,回调成功;

AFNetworking3.x不再需要线程保活

AFNetworking3.x是基于NSUrlSession实现的,NSUrlSession参考了AFN2.x的优点,自己维护了一个线程池,做Request线程的调度与管理;因此AFN3.x无需常驻线程,只是用的时候CFRunLoopRun();开启RunLoop,结束的时候CFRunLoopStop(CFRunLoopGetCurrent());停止RunLoop即可;

线程保活代码实现细节

参考AFN的实现,似乎我们只要依葫芦画瓢也能这样实现线程保活;但其中很多细节需要探究,接下来一步步分析:

为了监听线程的生命周期,先创建NSThread的子类;

@interface KeepThread : NSThread

@end

@implementation KeepThread

- (void)dealloc {
    NSLog(@"%s",__func__);
}

@end

然后依照AFN代码,创建线程;(这里使用block的方式代替了target的方式,因为target会对self强引用不利于分析内存问题);在开启RunLoop前后分别打印,以便查看代码执行状态;

- (IBAction)start:(id)sender {
    self.thread = [[KeepThread alloc] initWithBlock:^{
        NSLog(@"%@,start", [NSThread currentThread]);
        
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
        
        NSLog(@"%@,end", [NSThread currentThread]);
    }];
    [self.thread start];
}

然后点击vc的start按钮执行代码,结果是只打印了start,未输出end;

{number = 3, name = (null)},start

这是因为开启RunLoop并运行后,代码一直在[runloop run]这句代码循环,不会往下执行;block里的代码没有执行完,那么线程就不会退出、销毁;这样就达到了线程保活的作用,我们也可以从其他方面验证该线程一直存在着:

  • 退出当前vc,vc销毁;但是可以发现,KeepThread对象self.thread并未调用-dealloc方法,线程并不会销毁;
  • 添加一个点击事件,通过performSelector:onThread:在线程中执行代码:
- (void)dosomething {
    NSLog(@"%s",__func__);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(dosomething) onThread:self.thread withObject:nil waitUntilDone:NO];
}

每点击一次,会发现都能正常执行dosomething方法;这也说明线程一直存活,能被唤醒;

不过,以上代码,一个会令人疑惑的地方是[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];;runLoop中添加了NSMachPort,但是NSMachPort对象并没有用到;
NSMachPort的确没有其他实际用处,只是因为一个RunLoop如果没有任何要处理的事件时,就会退出;为了保证RunLoop不会一执行就退出就需要加上这段代码;
如果注释掉这句代码,那么就会输出以下结果,线程正常退出了;

{number = 3, name = (null)},start
{number = 3, name = (null)},end

而且这个也不是一定只能添加port事件,添加timer事件也能实现同样效果;只是port事件简单点;

[runLoop addTimer:timer forMode:NSDefaultRunLoopMode]
可控制的常驻线程

以上代码虽然实现了线程保活,但是并没有实现手动退出RunLoop,销毁线程的功能;而且经过上面的分析,这种方式的线程保活还存在内存泄漏的风险(因为thread释放不了,AFN的使用场景不同本身设计的就是永不释放同App生命周期一致);接下来我们就来尝试实现一个可控制的线程,即可以随时让保活的线程"死"去;
原理上讲,只要保证该线程的RunLoop停止,那么线程就能正常退出;接下来我们就添加一个按钮,当点击按钮时调用代码主动停止RunLoop:

- (IBAction)stop:(id)sender {
    [self performSelector:@selector(stopThread) onThread:self.thread withObject:nil waitUntilDone:NO];
}

- (void)stopThread {
    CFRunLoopStop(CFRunLoopGetCurrent());
}

令人意外的是,当点击停止后,没有任何输出,线程还是没有退出;

这个其实可以从RunLoop的run方法官方文档中找到答案:

If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers.
Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. macOS can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.
If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop. A simple example would be:

NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

大概意思是,run方法其实就是开启了一个无限循环,循环里调用runMode:beforeDate:运行RunLoop;因此我们调用CFRunLoopStop(CFRunLoopGetCurrent());只能退出exit一个RunLoop,但是并不能终止terminate外部的while循环;
也就是说以上代码其实就类似下面这段代码:

- (void)threadRun {
    @autoreleasepool {
        NSLog(@"%@,start", [NSThread currentThread]);
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        while (YES) {
            [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }

        NSLog(@"%@,end", [NSThread currentThread]);
    }
}

因此通过run方法开启的RunLoop无法终止;如果想终止,就需要使用 runMode:beforeDate:.方式,并使用一个BOOL变量控制while循环以此控制RunLoop;

可控制的线程保活的最终代码如下:

- (void)stopThread {
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.isStop = YES;
}

- (IBAction)start:(id)sender {
    __weak typeof (self) weakSelf = self;
    self.thread = [[KeepThread alloc] initWithBlock:^{
        NSLog(@"%@,start", [NSThread currentThread]);

        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        while (!weakSelf.isStop) {
            [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
        
        NSLog(@"%@,end", [NSThread currentThread]);
    }];
    [self.thread start];
}

参考:
AFNetworking3.0后为什么不再需要常驻线程?
深入研究 Runloop 与线程保活
深入理解RunLoop

你可能感兴趣的:(基于RunLoop进行线程保活的简单分析)