iOS runloop 源码流程验证探究
我们通过在 touchbegin 加一个断点,然后点击屏幕,然后再控制台输入 bt,来看见调用堆栈
bt
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1
* frame #0: 0x000000010d53acfd blogTest`-[ViewController touchesBegan:withEvent:](self=0x00007fa075707410, _cmd="touchesBegan:withEvent:", touches=1 element, event=0x0000600000fe8a00) at ViewController.m:149:5
frame #1: 0x0000000111329863 UIKitCore`forwardTouchMethod + 340
frame #2: 0x00000001113296fe UIKitCore`-[UIResponder touchesBegan:withEvent:] + 49
frame #3: 0x00000001113388de UIKitCore`-[UIWindow _sendTouchesForEvent:] + 1867
frame #4: 0x000000011133a4c6 UIKitCore`-[UIWindow sendEvent:] + 4596
frame #5: 0x000000011131553b UIKitCore`-[UIApplication sendEvent:] + 356
frame #6: 0x000000011139671a UIKitCore`__dispatchPreprocessedEventFromEventQueue + 6847
frame #7: 0x00000001113991e0 UIKitCore`__handleEventQueueInternal + 5980
frame #8: 0x000000010df65471 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
frame #9: 0x000000010df6539c CoreFoundation`__CFRunLoopDoSource0 + 76
frame #10: 0x000000010df64b74 CoreFoundation`__CFRunLoopDoSources0 + 180
frame #11: 0x000000010df5f87f CoreFoundation`__CFRunLoopRun + 1263
frame #12: 0x000000010df5f066 CoreFoundation`CFRunLoopRunSpecific + 438
frame #13: 0x0000000115928bb0 GraphicsServices`GSEventRunModal + 65
frame #14: 0x00000001112fcd4d UIKitCore`UIApplicationMain + 1621
frame #15: 0x000000010d53de94 blogTest`main(argc=1, argv=0x00007ffee26c5d60) at main.m:20:12
frame #16: 0x000000010f8c1c25 libdyld.dylib`start + 1
可以看到 是从 CFRunLoopRunSpecific 这个位置开始调用 runloop 的.
CFRunLoopRunSpecific
我们看下源码
SInt32 CFRunLoopRunSpecific(CFRunLoopRef rl, CFStringRef modeName, CFTimeInterval seconds, Boolean returnAfterSourceHandled) { /* DOES CALLOUT */
CHECK_FOR_FORK();
if (__CFRunLoopIsDeallocating(rl)) return kCFRunLoopRunFinished;
__CFRunLoopLock(rl);
CFRunLoopModeRef currentMode = __CFRunLoopFindMode(rl, modeName, false);
if (NULL == currentMode || __CFRunLoopModeIsEmpty(rl, currentMode, rl->_currentMode)) {
Boolean did = false;
if (currentMode) __CFRunLoopModeUnlock(currentMode);
__CFRunLoopUnlock(rl);
return did ? kCFRunLoopRunHandledSource : kCFRunLoopRunFinished;
}
volatile _per_run_data *previousPerRun = __CFRunLoopPushPerRunData(rl);
CFRunLoopModeRef previousMode = rl->_currentMode;
rl->_currentMode = currentMode;
int32_t result = kCFRunLoopRunFinished;
if (currentMode->_observerMask & kCFRunLoopEntry ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopEntry);
result = __CFRunLoopRun(rl, currentMode, seconds, returnAfterSourceHandled, previousMode);
if (currentMode->_observerMask & kCFRunLoopExit ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
__CFRunLoopModeUnlock(currentMode);
__CFRunLoopPopPerRunData(rl, previousPerRun);
rl->_currentMode = previousMode;
__CFRunLoopUnlock(rl);
return result;
}
我们可以看到这样一句话啊
// 通知 observer 进入
if (currentMode->_observerMask & kCFRunLoopEntry ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopEntry);
// 开始 run
result = __CFRunLoopRun(rl, currentMode, seconds, returnAfterSourceHandled, previousMode);
// 通知 observer 退出
if (currentMode->_observerMask & kCFRunLoopExit ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
我们接着看下 __CFRunLoopRun 这个函数
这段源码特别长,但是我们为了看流程,这段代码里面有这样一段
// 处理 timer 事件
if (rlm->_observerMask & kCFRunLoopBeforeTimers) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeTimers);、
// 处理 source 事件
if (rlm->_observerMask & kCFRunLoopBeforeSources) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeSources);
、// 处理block
__CFRunLoopDoBlocks(rl, rlm);
Boolean poll = sourceHandledThisLoop || (0ULL == timeout_context->termTSR);
// 处理 port,也就是source1事件
if (MACH_PORT_NULL != dispatchPort && !didDispatchPortLastTime) {
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
msg = (mach_msg_header_t *)msg_buffer;
if (__CFRunLoopServiceMachPort(dispatchPort, &msg, sizeof(msg_buffer), &livePort, 0)) {
goto handle_msg;
}
#elif DEPLOYMENT_TARGET_WINDOWS
if (__CFRunLoopWaitForMultipleObjects(NULL, &dispatchPort, 0, 0, &livePort, NULL)) {
goto handle_msg;
}
#endif
}
// 即将休眠
if (!poll && (rlm->_observerMask & kCFRunLoopBeforeWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeWaiting);
__CFRunLoopSetSleeping(rl)
// 等待别的线程唤醒
__CFRunLoopServiceMachPort(waitSet, &msg, sizeof(msg_buffer), &livePort, poll ? 0 : TIMEOUT_INFINITY);
// 结束休眠
__CFRunLoopUnsetSleeping(rl);
if (!poll && (rlm->_observerMask & kCFRunLoopAfterWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopAfterWaiting);
可以看到,和我们之前分析的是一样的,先处理 timer事件,然后处理 sources 事件,紧接着处理 block,紧接着判断是否有 source1 事件,有的话就回去处理,如果没有,就会进入即将休眠事件,然后开始休眠,等待消息唤醒它,然后结束休眠,都是通过 __CFRunLoopDoObservers 这个函数来通知的。
其中 __CFRunLoopServiceMachPort 是让当前线程休眠,内部调用了 mach_msg 函数,是个内核函数,用户态向内核态的 转化,他的作用是等待消息唤醒,没有消息就让线程休眠,有消息了就唤醒线程。当唤醒的时候又从内核态切换到了用户态。