目录
RunLoop是什么
RunLoop - Event Loop / Event Dispatcher
function loop() {
initialize();
do {
var message = get_next_message();
process_message(message);
if (!get_next_message()) {
sleepForAwake();
}
} while (message != quit);
}
NSRunLoop is not thread-safe!
So its methods should only be called within the context of the current thread
RunLoop与线程
CFRunLoop.c(基于CF-1153.18.tar.gz)
// should only be called by Foundation
// t==0 is a synonym for "main thread" that always works
CF_EXPORT CFRunLoopRef _CFRunLoopGet0(pthread_t t) {
if (pthread_equal(t, kNilPthreadT)) {
t = pthread_main_thread_np();
}
__CFLock(&loopsLock);
if (!__CFRunLoops) {
__CFUnlock(&loopsLock);
CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
CFRunLoopRef mainLoop = __CFRunLoopCreate(pthread_main_thread_np());
CFDictionarySetValue(dict, pthreadPointer(pthread_main_thread_np()), mainLoop);
if (!OSAtomicCompareAndSwapPtrBarrier(NULL, dict, (void * volatile *)&__CFRunLoops)) {
CFRelease(dict);
}
CFRelease(mainLoop);
__CFLock(&loopsLock);
}
CFRunLoopRef loop = (CFRunLoopRef)CFDictionaryGetValue(__CFRunLoops, pthreadPointer(t));
__CFUnlock(&loopsLock);
if (!loop) {
CFRunLoopRef newLoop = __CFRunLoopCreate(t);
__CFLock(&loopsLock);
loop = (CFRunLoopRef)CFDictionaryGetValue(__CFRunLoops, pthreadPointer(t));
if (!loop) {
CFDictionarySetValue(__CFRunLoops, pthreadPointer(t), newLoop);
loop = newLoop;
}
// don't release run loops inside the loopsLock, because CFRunLoopDeallocate may end up taking it
__CFUnlock(&loopsLock);
CFRelease(newLoop);
}
if (pthread_equal(t, pthread_self())) {
_CFSetTSD(__CFTSDKeyRunLoop, (void *)loop, NULL);
if (0 == _CFGetTSD(__CFTSDKeyRunLoopCntr)) {
_CFSetTSD(__CFTSDKeyRunLoopCntr, (void *)(PTHREAD_DESTRUCTOR_ITERATIONS-1), (void (*)(void *))__CFFinalizeRunLoop);
}
}
return loop;
}
CFRunLoopRef CFRunLoopGetMain(void) {
CHECK_FOR_FORK();
static CFRunLoopRef __main = NULL; // no retain needed
if (!__main) __main = _CFRunLoopGet0(pthread_main_thread_np()); // no CAS needed
return __main;
}
CFRunLoopRef CFRunLoopGetCurrent(void) {
CHECK_FOR_FORK();
CFRunLoopRef rl = (CFRunLoopRef)_CFGetTSD(__CFTSDKeyRunLoop);
if (rl) return rl;
return _CFRunLoopGet0(pthread_self());
}
结论
不允许直接创建RunLoop
RunLoop和线程是一一对应的
RunLoop和线程的一一对应关系保存一个全局Dictionary里
线程刚创建时并没有RunLoop, 如果你不主动获取, 那它一直都不会有(main thread除外)
你只能在一个线程的内部获取其RunLoop(main thread除外)
RunLoop的概念
A CFRunLoop object monitors sources of input to a task and dispatches control when they become ready for processing
CFRunLoopRef is thread-safe
Examples of input sources might include
input devices, network connections
periodic or time-delayed events
asynchronous callbacks
Three types of objects can be monitored by a run loop
sources - CFRunLoopSourceRef
timers - CFRunLoopTimerRef
observers - CFRunLoopObserverRef
RunLoop Mode
A run loop mode is a collection of input sources and timers to be monitored and a collection of run loop observers to be notified
Each time you run your run loop, you specify (either explicitly or implicitly) a particular “mode” in which to run
Only sources associated with that mode are monitored and allowed to deliver their events
Predefined run loop modes list
NSDefaultRunLoopMode, The default mode is the one used for most operations
UITrackingRunLoopMode, The mode set while tracking in controls takes place
NSConnectionReplyMode, Cocoa uses this mode in conjunction with NSConnection objects to monitor replies
NSRunLoopCommonModes, This is a configurable group of commonly used modes
iOS开发 之 不要告诉我你会用NSTimer有NSTimer与Runloop Mode的实际应用
RunLoop的实现
CFRunLoop.c(基于CF-1153.18.tar.gz)
/* rl, rlm are locked on entrance and exit */
static int32_t __CFRunLoopRun(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFTimeInterval seconds, Boolean stopAfterHandle, CFRunLoopModeRef previousMode) {
// 核心实现, 不过代码太长, 就不继续贴了
}
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;
}
void CFRunLoopRun(void) { /* DOES CALLOUT */
int32_t result;
do {
result = CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
CHECK_FOR_FORK();
} while (kCFRunLoopRunStopped != result && kCFRunLoopRunFinished != result);
}
The Run Loop Sequence of Events
(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.
原版的描述准确而不"生动", 这里借用ibireme的图如下
RunLoop的应用
在实际应用中, RunLoop是通过一串命名很长的回调函数反馈给上层App的
这里仍然借用的ibireme整理结果
{
/// 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);
}
事件响应
#0 0x00000001000d71d8 in -[ViewController buttonOnClicked:] at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/ViewController.m:43
#1 0x0000000187b4cbe8 in -[UIApplication sendAction:to:from:forEvent:] ()
#2 0x0000000187b4cb64 in -[UIControl sendAction:to:forEvent:] ()
#3 0x0000000187b34870 in -[UIControl _sendActionsForEvents:withEvent:] ()
#4 0x0000000187b4c454 in -[UIControl touchesEnded:withEvent:] ()
#5 0x0000000187b4c084 in -[UIWindow _sendTouchesForEvent:] ()
#6 0x0000000187b44c20 in -[UIWindow sendEvent:] ()
#7 0x0000000187b1504c in -[UIApplication sendEvent:] ()
#8 0x0000000187b13628 in _UIApplicationHandleEventQueue ()
#9 0x000000018296d09c in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ ()
#10 0x000000018296cb30 in __CFRunLoopDoSources0 ()
#11 0x000000018296a830 in __CFRunLoopRun ()
#12 0x0000000182894c50 in CFRunLoopRunSpecific ()
#13 0x000000018417c088 in GSEventRunModal ()
#14 0x0000000187b7e088 in UIApplicationMain ()
#15 0x00000001000d8fc0 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#16 0x00000001824328b8 in start ()
界面更新
#0 0x00000001000d4f1c in -[KYView drawRect:] at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/KYView.m:14
#1 0x0000000187b9e678 in -[UIView(CALayerDelegate) drawLayer:inContext:] ()
#2 0x00000001854d2230 in -[CALayer drawInContext:] ()
#3 0x00000001854bc8b4 in CABackingStoreUpdate_ ()
#4 0x00000001855d4360 in ___ZN2CA5Layer8display_Ev_block_invoke ()
#5 0x00000001854bba90 in CA::Layer::display_() ()
#6 0x000000018549d7b0 in CA::Layer::display_if_needed(CA::Transaction*) ()
#7 0x000000018549d49c in CA::Layer::layout_and_display_if_needed(CA::Transaction*) ()
#8 0x000000018549cac0 in CA::Context::commit_transaction(CA::Transaction*) ()
#9 0x000000018549c820 in CA::Transaction::commit() ()
#10 0x0000000185495de4 in CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) ()
#11 0x000000018296c728 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ ()
#12 0x000000018296a4cc in __CFRunLoopDoObservers ()
#13 0x0000000182894c70 in CFRunLoopRunSpecific ()
#14 0x0000000187b8394c in -[UIApplication _run] ()
#15 0x0000000187b7e088 in UIApplicationMain ()
#16 0x00000001000d4fc0 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#17 0x00000001824328b8 in start ()
AutoreleasePool
#0 0x0000000100035344 in -[SecondView dealloc] at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/SecondView.m:18
#1 0x0000000182035ae8 in (anonymous namespace)::AutoreleasePoolPage::pop(void*) ()
#2 0x00000001828949fc in _CFAutoreleasePoolPop ()
#3 0x000000018296abc0 in __CFRunLoopRun ()
#4 0x0000000182894c50 in CFRunLoopRunSpecific ()
#5 0x000000018417c088 in GSEventRunModal ()
#6 0x0000000187b7e088 in UIApplicationMain ()
#7 0x0000000100044a50 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#8 0x00000001824328b8 in start ()
定时器
#0 0x00000001000d75b4 in -[ViewController timerSelector:] at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/ViewController.m:64
#1 0x000000018338d038 in __NSFireTimer ()
#2 0x000000018296d794 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ ()
#3 0x000000018296d438 in __CFRunLoopDoTimer ()
#4 0x000000018296ab4c in __CFRunLoopRun ()
#5 0x0000000182894c50 in CFRunLoopRunSpecific ()
#6 0x000000018417c088 in GSEventRunModal ()
#7 0x0000000187b7e088 in UIApplicationMain ()
#8 0x00000001000d8fc0 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#9 0x00000001824328b8 in start ()
GCD
#0 0x00000001000d7428 in __40-[ViewController afnetworkingOnClicked:]_block_invoke_2 at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/ViewController.m:52
#1 0x00000001000f14c4 in __116-[AFHTTPSessionManager dataTaskWithHTTPMethod:URLString:parameters:uploadProgress:downloadProgress:success:failure:]_block_invoke.97 at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/AFNetworking/AFHTTPSessionManager.m:277
#2 0x00000001000cc8c8 in __72-[AFURLSessionManagerTaskDelegate URLSession:task:didCompleteWithError:]_block_invoke_2.150 at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/AFNetworking/AFURLSessionManager.m:304
#3 0x000000010018da7c in _dispatch_call_block_and_release ()
#4 0x000000010018da3c in _dispatch_client_callout ()
#5 0x00000001001934e4 in _dispatch_main_queue_callback_4CF ()
#6 0x000000018296cd50 in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#7 0x000000018296abb8 in __CFRunLoopRun ()
#8 0x0000000182894c50 in CFRunLoopRunSpecific ()
#9 0x000000018417c088 in GSEventRunModal ()
#10 0x0000000187b7e088 in UIApplicationMain ()
#11 0x00000001000d8fc0 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#12 0x00000001824328b8 in start ()
空闲
#0 0x0000000182534fd8 in mach_msg_trap ()
#1 0x0000000182534e54 in mach_msg ()
#2 0x000000018296cc60 in __CFRunLoopServiceMachPort ()
#3 0x000000018296a964 in __CFRunLoopRun ()
#4 0x0000000182894c50 in CFRunLoopRunSpecific ()
#5 0x000000018417c088 in GSEventRunModal ()
#6 0x0000000187b7e088 in UIApplicationMain ()
#7 0x00000001000d8fc0 in main at /Users/yuanlin/Workspace/ios-tutorial/RunLoopDemo/RunLoopDemo/main.m:14
#8 0x00000001824328b8 in start ()
完整的Demo源码参考RunLoopDemo
附录
更多文章, 请支持我的个人博客