一个苹果

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

2020-01-04  本文已影响0人  _小沫

线程与RunLoop

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

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线程保活的作用

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;

<KeepThread: 0x6000022695c0>{number = 3, name = (null)},start

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

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

- (void)touchesBegan:(NSSet<UITouch *> *)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不会一执行就退出就需要加上这段代码;
如果注释掉这句代码,那么就会输出以下结果,线程正常退出了;

<KeepThread: 0x600003cabfc0>{number = 3, name = (null)},start
<KeepThread: 0x600003cabfc0>{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

上一篇 下一篇

猜你喜欢

热点阅读