欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

RunLoop总结:RunLoop的应用场景(四)

程序员文章站 2022-08-09 18:12:13
runloop总结:runloop的应用场景(四) 今天要介绍的runloop使用场景很有意思,在做长期项目,需要跟踪解决用户问题非常有用。 使用runloop 监测主线程的卡顿,并将卡顿时的线程堆...

runloop总结:runloop的应用场景(四)

今天要介绍的runloop使用场景很有意思,在做长期项目,需要跟踪解决用户问题非常有用。
使用runloop 监测主线程的卡顿,并将卡顿时的线程堆栈信息保存下来,下次上传到服务器。

参考资料

关于今天要介绍的使用runloop 监测主线程卡顿的资料如下:
* 微信ios卡顿监控 (这篇文章要首先,了解有哪些情况会引起主线程卡顿,监测到卡顿后怎么处理等)
* 监控卡顿的方法 (使用runloop监测卡顿的片段代码)
* 简单监测ios卡顿的demo (使用runloop监测卡顿的例子)

原理

官方文档说明了runloop的执行顺序:

1. notify observers that the run loop has been entered.
2. notify observers that any ready timers are about to fire.
3. notify observers that any input sources that are not port based are about to fire.
4. fire any non-port-based input sources that are ready to fire.
5. if a port-based input source is ready and waiting to fire, process the event immediately. go to step 9.
6. notify observers that the thread is about to sleep.
7. put the thread to sleep until one of the following events occurs:
 * an event arrives for a port-based input source.
 * a timer fires.
 * the timeout value set for the run loop expires.
 * the run loop is explicitly woken up.
8. notify observers that the thread just woke up.
9. process the pending event.
 * if a user-defined timer fired, process the timer event and restart the loop. go to step 2.
 * if an input source fired, deliver the event.
 * if the run loop was explicitly woken up but has not yet timed out, restart the loop. go to step 2.
10. notify observers that the run loop has exited.

用伪代码来实现就是这样的:

{
    /// 1. 通知observers,即将进入runloop
    /// 此处有observer会创建autoreleasepool: _objc_autoreleasepoolpush();
    __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopentry);
    do {

        /// 2. 通知 observers: 即将触发 timer 回调。
        __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopbeforetimers);
        /// 3. 通知 observers: 即将触发 source (非基于port的,source0) 回调。
        __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopbeforesources);
        __cfrunloop_is_calling_out_to_a_block__(block);

        /// 4. 触发 source0 (非基于port的) 回调。
        __cfrunloop_is_calling_out_to_a_source0_perform_function__(source0);
        __cfrunloop_is_calling_out_to_a_block__(block);

        /// 6. 通知observers,即将进入休眠
        /// 此处有observer释放并新建autoreleasepool: _objc_autoreleasepoolpop(); _objc_autoreleasepoolpush();
        __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopbeforewaiting);

        /// 7. sleep to wait msg.
        mach_msg() -> mach_msg_trap();


        /// 8. 通知observers,线程被唤醒
        __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopafterwaiting);

        /// 9. 如果是被timer唤醒的,回调timer
        __cfrunloop_is_calling_out_to_a_timer_callback_function__(timer);

        /// 9. 如果是被dispatch唤醒的,执行所有调用 dispatch_async 等方法放入main queue 的 block
        __cfrunloop_is_servicing_the_main_dispatch_queue__(dispatched_block);

        /// 9. 如果如果runloop是被 source1 (基于port的) 的事件唤醒了,处理这个事件
        __cfrunloop_is_calling_out_to_a_source1_perform_function__(source1);


    } while (...);

    /// 10. 通知observers,即将退出runloop
    /// 此处有observer释放autoreleasepool: _objc_autoreleasepoolpop();
    __cfrunloop_is_calling_out_to_an_observer_callback_function__(kcfrunloopexit);
}

主线程的runloop是在应用启动时自动开启的,也没有超时时间,所以正常情况下,主线程的runloop 只会在 2—9 之间无限循环下去。
那么,我们只需要在主线程的runloop中添加一个observer,检测从 kcfrunloopbeforesources 到 kcfrunloopbeforewaiting 花费的时间 是否过长。如果花费的时间大于某一个阙值,我们就认为有卡顿,并把当前的线程堆栈转储到文件中,并在以后某个合适的时间,将卡顿信息文件上传到服务器。

实现步骤

在看了上面的两个监测卡顿的示例demo后,我按照上面讲述的思路写了一个demo,应该更容易理解吧。
第一步,创建一个子线程,在线程启动时,启动其runloop。

+ (instancetype)sharemonitor
{
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        instance = [[[self class] alloc] init];
        instance.monitorthread = [[nsthread alloc] initwithtarget:self selector:@selector(monitorthreadentrypoint) object:nil];
        [instance.monitorthread start];
    });

    return instance;
}

+ (void)monitorthreadentrypoint
{
    @autoreleasepool {
        [[nsthread currentthread] setname:@"fluencymonitor"];
        nsrunloop *runloop = [nsrunloop currentrunloop];
        [runloop addport:[nsmachport port] formode:nsdefaultrunloopmode];
        [runloop run];
    }
}

第二步,在开始监测时,往主线程的runloop中添加一个observer,并往子线程中添加一个定时器,每0.5秒检测一次耗时的时长。

- (void)start
{
    if (_observer) {
        return;
    }

    // 1.创建observer
    cfrunloopobservercontext context = {0,(__bridge void*)self, null, null, null};
    _observer = cfrunloopobservercreate(kcfallocatordefault,
                                              kcfrunloopallactivities,
                                              yes,
                                              0,
                                              &runloopobservercallback,
                                              &context);
    // 2.将observer添加到主线程的runloop中
    cfrunloopaddobserver(cfrunloopgetmain(), _observer, kcfrunloopcommonmodes);

    // 3.创建一个timer,并添加到子线程的runloop中
    [self performselector:@selector(addtimertomonitorthread) onthread:self.monitorthread withobject:nil waituntildone:no modes:@[nsrunloopcommonmodes]];
}

- (void)addtimertomonitorthread
{
    if (_timer) {
        return;
    }
    // 创建一个timer
    cfrunloopref currentrunloop = cfrunloopgetcurrent();
    cfrunlooptimercontext context = {0, (__bridge void*)self, null, null, null};
    _timer = cfrunlooptimercreate(kcfallocatordefault, 0.1, 0.01, 0, 0,
                                                   &runlooptimercallback, &context);
    // 添加到子线程的runloop中
    cfrunloopaddtimer(currentrunloop, _timer, kcfrunloopcommonmodes);
}

第三步,补充观察者回调处理

static void runloopobservercallback(cfrunloopobserverref observer, cfrunloopactivity activity, void *info){
    fluencymonitor *monitor = (__bridge fluencymonitor*)info;
    nslog(@"mainrunloop---%@",[nsthread currentthread]);
    switch (activity) {
        case kcfrunloopentry:
            nslog(@"kcfrunloopentry");
            break;
        case kcfrunloopbeforetimers:
            nslog(@"kcfrunloopbeforetimers");
            break;
        case kcfrunloopbeforesources:
            nslog(@"kcfrunloopbeforesources");
            monitor.startdate = [nsdate date];
            monitor.excuting = yes;
            break;
        case kcfrunloopbeforewaiting:
            nslog(@"kcfrunloopbeforewaiting");
            monitor.excuting = no;
            break;
        case kcfrunloopafterwaiting:
            nslog(@"kcfrunloopafterwaiting");
            break;
        case kcfrunloopexit:
            nslog(@"kcfrunloopexit");
            break;
        default:
            break;
    }
}

从打印信息来看,runloop进入睡眠状态的时间可能会非常短,有时候只有1毫秒,有时候甚至1毫秒都不到,静止不动时,则会长时间进入睡觉状态。

因为主线程中的block、交互事件、以及其他任务都是在kcfrunloopbeforesources 到 kcfrunloopbeforewaiting 之前执行,所以我在即将开始执行sources 时,记录一下时间,并把正在执行任务的标记置为yes,将要进入睡眠状态时,将正在执行任务的标记置为no。

第四步,补充timer 的回调处理

static void runlooptimercallback(cfrunlooptimerref timer, void *info)
{
    fluencymonitor *monitor = (__bridge fluencymonitor*)info;
    if (!monitor.excuting) {
        return;
    }

    // 如果主线程正在执行任务,并且这一次loop 执行到 现在还没执行完,那就需要计算时间差
    nstimeinterval excutetime = [[nsdate date] timeintervalsincedate:monitor.startdate];
    nslog(@"定时器---%@",[nsthread currentthread]);
    nslog(@"主线程执行了---%f秒",excutetime);

    if (excutetime >= 0.01) {
        nslog(@"线程卡顿了%f秒",excutetime);
        [monitor handlestackinfo];
    }
}

timer 每 0.01秒执行一次,如果当前正在执行任务的状态为yes,并且从开始执行到现在的时间大于阙值,则把堆栈信息保存下来,便于后面处理。
为了能够捕获到堆栈信息,我把timer的间隔调的很小(0.01),而评定为卡顿的阙值也调的很小(0.01)。 实际使用时这两个值应该是比较大,timer间隔为1s,卡顿阙值为2s即可。

2016-12-15 08:56:39.921 runloopdemo03[957:16300] lag happen, detail below: 
 incident identifier: 68bab24c-3224-46c8-89bf-f9aaba2e3530
crashreporter key:   todo
hardware model:      x86_64
process:         runloopdemo03 [957]
path:            /users/harvey/library/developer/coresimulator/devices/6ed39dbb-9f69-4acb-9ce3-e6eb56bbfece/data/containers/bundle/application/5a94defe-4e2e-4d23-9f69-7b1954b2c960/runloopdemo03.app/runloopdemo03
identifier:      com.haley.runloopdemo03
version:         1.0 (1)
code type:       x86-64
parent process:  debugserver [958]

date/time:       2016-12-15 00:56:38 +0000
os version:      mac os x 10.1 (16a323)
report version:  104

exception type:  sigtrap
exception codes: trap_trace at 0x1063da728
crashed thread:  4

thread 0:
0   libsystem_kernel.dylib              0x000000010a14341a mach_msg_trap + 10
1   corefoundation                      0x0000000106f1e7b4 __cfrunloopservicemachport + 212
2   corefoundation                      0x0000000106f1dc31 __cfrunlooprun + 1345
3   corefoundation                      0x0000000106f1d494 cfrunlooprunspecific + 420
4   graphicsservices                    0x000000010ad8aa6f gseventrunmodal + 161
5   uikit                               0x00000001073b7964 uiapplicationmain + 159
6   runloopdemo03                       0x00000001063dbf8f main + 111
7   libdyld.dylib                       0x0000000109d7468d start + 1

thread 1:
0   libsystem_kernel.dylib              0x000000010a14be5e kevent_qos + 10
1   libdispatch.dylib                   0x0000000109d13074 _dispatch_mgr_invoke + 248
2   libdispatch.dylib                   0x0000000109d12e76 _dispatch_mgr_init + 0

thread 2:
0   libsystem_kernel.dylib              0x000000010a14b4e6 __workq_kernreturn + 10
1   libsystem_pthread.dylib             0x000000010a16e221 start_wqthread + 13

thread 3:
0   libsystem_kernel.dylib              0x000000010a14341a mach_msg_trap + 10
1   corefoundation                      0x0000000106f1e7b4 __cfrunloopservicemachport + 212
2   corefoundation                      0x0000000106f1dc31 __cfrunlooprun + 1345
3   corefoundation                      0x0000000106f1d494 cfrunlooprunspecific + 420
4   foundation                          0x00000001064d7ff0 -[nsrunloop runmode:beforedate:] + 274
5   foundation                          0x000000010655f991 -[nsrunloop rununtildate:] + 78
6   uikit                               0x0000000107e3d539 -[uieventfetcher threadmain] + 118
7   foundation                          0x00000001064e7ee4 __nsthread__start__ + 1243
8   libsystem_pthread.dylib             0x000000010a16eabb _pthread_body + 180
9   libsystem_pthread.dylib             0x000000010a16ea07 _pthread_body + 0
10  libsystem_pthread.dylib             0x000000010a16e231 thread_start + 13

thread 4 crashed:
0   runloopdemo03                       0x00000001063dfae5 -[plcrashreporter generatelivereportwiththread:error:] + 632
1   runloopdemo03                       0x00000001063da728 -[fluencymonitor handlestackinfo] + 152
2   runloopdemo03                       0x00000001063da2cf runlooptimercallback + 351
3   corefoundation                      0x0000000106f26964 __cfrunloop_is_calling_out_to_a_timer_callback_function__ + 20
4   corefoundation                      0x0000000106f265f3 __cfrunloopdotimer + 1075
5   corefoundation                      0x0000000106f2617a __cfrunloopdotimers + 250
6   corefoundation                      0x0000000106f1df01 __cfrunlooprun + 2065
7   corefoundation                      0x0000000106f1d494 cfrunlooprunspecific + 420
8   foundation                          0x00000001064d7ff0 -[nsrunloop runmode:beforedate:] + 274
9   foundation                          0x00000001064d7ecb -[nsrunloop run] + 76
10  runloopdemo03                       0x00000001063d9cbd +[fluencymonitor monitorthreadentrypoint] + 253
11  foundation                          0x00000001064e7ee4 __nsthread__start__ + 1243
12  libsystem_pthread.dylib             0x000000010a16eabb _pthread_body + 180
13  libsystem_pthread.dylib             0x000000010a16ea07 _pthread_body + 0
14  libsystem_pthread.dylib             0x000000010a16e231 thread_start + 13

thread 4 crashed with x86-64 thread state:
   rip: 0x00000001063dfae5    rbp: 0x000070000f53fc50    rsp: 0x000070000f53f9c0    rax: 0x000070000f53fa20 
   rbx: 0x000070000f53fb60    rcx: 0x0000000000005e0b    rdx: 0x0000000000000000    rdi: 0x00000001063dfc6a 
   rsi: 0x000070000f53f9f0     r8: 0x0000000000000014     r9: 0xffffffffffffffec    r10: 0x000000010a1433f6 
   r11: 0x0000000000000246    r12: 0x000060800016b580    r13: 0x0000000000000000    r14: 0x0000000000000006 
   r15: 0x000070000f53fa40 rflags: 0x0000000000000206     cs: 0x000000000000002b     fs: 0x0000000000000000 
    gs: 0x0000000000000000 

剩下的工作就是将字符串保存进文件,以及上传到服务器了。

我们不能将卡顿的阙值定的太小,也不能将所有的卡顿信息都上传,原因有两点,一,太浪费用户流量;二、文件太多,app内存储和上传后服务器端保存都会占用空间。

可以参考微信的做法,7天以上的文件删除,随机抽取上传,并且上传前对文件进行压缩处理等。