iOS 性能监控(二)—— 主线程卡顿监控

//! 创建子线程监控

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        //! 子线程开启一个持续的loop用来进行监控

        while (YES) {

            long semaphoreWait = dispatch_semaphore_wait(self->dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, STUCKMONITORRATE * NSEC_PER_MSEC));

            if (semaphoreWait != 0) {

                if (!self->runLoopObserver) {

                    self->timeoutCount = 0;

                    self->dispatchSemaphore = 0;

                    self->runLoopActivity = 0;

                    return;

                }

                //! 两个runloop的状态,BeforeSources和AfterWaiting这两个状态区间时间能够检测到是否卡顿

                if (self->runLoopActivity == kCFRunLoopBeforeSources || self->runLoopActivity == kCFRunLoopAfterWaiting) {

                    //! 出现三次出结果

                    if (++self->timeoutCount < 3) {

                        continue;

                    }

                    NSLog(@"monitor trigger");

                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

                        NSString *stackStr = [QiCallStack callStackWithType:QiCallStackTypeMain];

                        QiCallStackModel *model = [[QiCallStackModel alloc] init];

                        model.stackStr = stackStr;

                        model.isStuck = YES;

                        [[[QiLagDB shareInstance] increaseWithStackModel:model] subscribeNext:^(id x) {}];

                    });

                } // end activity

            }// end semaphore wait

            self->timeoutCount = 0;

        }// end while

});