iOS开发 之 RunLoop(精华版)

目录

RunLoop是什么

RunLoop - Event Loop / Event Dispatcher

NSRunLoop Reference

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

CFRunLoop Reference

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

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-01.png

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

附录

更多文章, 请支持我的个人博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,776评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,527评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,361评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,430评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,511评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,544评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,561评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,315评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,763评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,070评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,235评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,911评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,554评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,173评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,424评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,106评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,103评论 2 352

推荐阅读更多精彩内容