RunLoop总结:RunLoop的应用场景(四).doc_第1页
RunLoop总结:RunLoop的应用场景(四).doc_第2页
RunLoop总结:RunLoop的应用场景(四).doc_第3页
RunLoop总结:RunLoop的应用场景(四).doc_第4页
RunLoop总结:RunLoop的应用场景(四).doc_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

RunLoop总结: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 只会在 29 之间无限循环下去。 那么,我们只需要在主线程的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 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 RunLoopDemo03957:16300 lag happen, detail below: Incident Identifier: 68BAB24C-3224-46C8-89BF-F9AABA2E3530CrashReporter Key: TODOHardware Model: x86_64Process: RunLoopDemo03 957Path: /Users/harvey/Library/Developer/CoreSimulator/Devices/6ED39DBB-9F69-4ACB-9CE3-E6EB56BBFECE/data/Containers/Bundle/Application/5A94DEFE-4E2E-4D23-9F69-7B1954B2C960/RunLoopDemo03.app/RunLoopDemo03Identifier: com.Haley.RunLoopDemo03Version: 1.0 (1)Code Type: X86-64Parent Process: debugserver 958Date/Time: 2016-12-15 00:56:38 +0000OS Version: Mac OS X 10.1 (16A323)Report Version: 104Exception Type: SIGTRAPException Codes: TRAP_TRACE at 0x1063da728Crashed Thread: 4Thread 0:0 libsystem_kernel.dylib 0x000000010a14341a mach_msg_trap + 101 CoreFoundation 0x0000000106f1e7b4 _CFRunLoopServiceMachPort + 2122 CoreFoundation 0x0000000106f1dc31 _CFRunLoopRun + 13453 CoreFoundation 0x0000000106f1d494 CFRunLoopRunSpecific + 4204 GraphicsServices 0x000000010ad8aa6f GSEventRunModal + 1615 UIKit 0x00000001073b7964 UIApplicationMain + 1596 RunLoopDemo03 0x00000001063dbf8f main + 1117 libdyld.dylib 0x0000000109d7468d start + 1Thread 1:0 libsystem_kernel.dylib 0x000000010a14be5e kevent_qos + 101 libdispatch.dylib 0x0000000109d13074 _dispatch_mgr_invoke + 2482 libdispatch.dylib 0x0000000109d12e76 _dispatch_mgr_init + 0Thread 2:0 libsystem_kernel.dylib 0x000000010a14b4e6 _workq_kernreturn + 101 libsystem_pthread.dylib 0x000000010a16e221 start_wqthread + 13Thread 3:0 libsystem_kernel.dylib 0x000000010a14341a mach_msg_trap + 101 CoreFoundation 0x0000000106f1e7b4 _CFRunLoopServiceMachPort + 2122 CoreFoundation 0x0000000106f1dc31 _CFRunLoopRun + 13453 CoreFoundation 0x0000000106f1d494 CFRunLoopRunSpecific + 4204 Foundation 0x00000001064d7ff0 -NSRunLoop runMode:beforeDate: + 2745 Foundation 0x000000010655f991 -NSRunLoop runUntilDate: + 786 UIKit 0x0000000107e3d539 -UIEventFetcher threadMain + 1187 Foundation 0x00000001064e7ee4 _NSThread_start_ + 12438 libsystem_pthread.dylib 0x000000010a16eabb _pthread_body + 1809 libsystem_pthread.dylib 0x000000010a16ea07 _pthread_body + 010 libsystem_pthread.dylib 0x000000010a16e231 thread_start + 13Thread 4 Crashed:0 RunLoopDemo03 0x00000001063dfae5 -PLCrashReporter generateLiveReportWithThread:error: + 6321 RunLoopDemo03 0x00000001063da728 -FluencyMonitor handleStackInfo + 1522 RunLoopDemo03 0x00000001063da2cf runLoopTimerCallBack + 3513 CoreFoundation 0x0000000106f26964 _CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION_ + 204 CoreFoundation 0x0000000106f265f3 _CFRunLoopDoTimer + 10755 CoreFoundation 0x0000000106f2617a _CFRunLoopDoTimers + 2506 CoreFoundation 0x0000000106f1df01 _CFRunLoopRun + 20657 CoreFoundation 0x0000000106f1d494 CFRunLoopRunSpecific + 4208 Foundation 0x00000001064d7ff0 -NSRunLoop runMode:beforeDate: + 2749 Foundation 0x00000001064d7ecb -NSRunLoop run + 7610 RunLoop

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论