iOS RunLoop底層探索

【原創(chuàng)博文强挫,轉(zhuǎn)載請(qǐng)注明出處鸽素!】

CFRunLoopRef源碼在此!

RunLoop:運(yùn)行循環(huán)举哟,在程序運(yùn)行過(guò)程中循環(huán)做一些事情思劳。所涉及的范疇包括:
① 定時(shí)器;
② GCD Async Main Queue;
③ 事件響應(yīng)妨猩、手勢(shì)識(shí)別潜叛、界面刷新;
④ 網(wǎng)絡(luò)請(qǐng)求壶硅;
⑤ AutoreleasePool威兜。

RunLoop_Circle.png

通常情況下如果我們創(chuàng)建一個(gè)Command Line Tool項(xiàng)目,如下:

Mac上面 Command Line Tool項(xiàng)目的main函數(shù).png

程序在執(zhí)行到Line13之后庐椒,馬上會(huì)執(zhí)行Line15椒舵,然后程序退出。
然而在我們的iOS項(xiàng)目中约谈,main函數(shù)可不是這么寫(xiě)的笔宿。

iOS項(xiàng)目中main函數(shù).png
runloop大概做的事情類似于do...while循環(huán).png

有了RunLoop,程序并不會(huì)馬上退出棱诱,而是保持運(yùn)行狀態(tài)泼橘。RunLoop可以處理App中的各種事件(比如觸摸事件、定時(shí)器事件等)军俊;RunLoop可以在該做事的時(shí)候做事侥加,該休息的時(shí)候休息捧存,從而節(jié)約CPU資源粪躬,提高程序性能。

iOS中提供兩套API來(lái)訪問(wèn)和使用RunLoop昔穴,分別為Foundation框架下面的NSRunLoop和Core Foundation下面的CFRunLoopRef镰官。
NSRunLoop和CFRunLoopRef都是RunLoop對(duì)象,其中NSRunLoop是基于CFRunLoopRef的一層OC包裝(參考圖NSRunLoop是基于CFRunLoopRef的一層OC包裝.png)吗货,CFRunLoopRef是開(kāi)源的泳唠,開(kāi)源地址已經(jīng)在上文給出。

NSRunLoop是基于CFRunLoopRef的一層OC包裝.png

上圖中宙搬,touch事件在主線程中觸發(fā)笨腥,主線程所對(duì)應(yīng)的RunLoop為mainRunLoop拓哺,通過(guò)OC與C語(yǔ)言的API訪問(wèn)RunLoop地址,可見(jiàn)兩者指針不同脖母,但是NSLog(@"%@",[NSRunLoop currentRunLoop]);輸出的RunLoop詳細(xì)信息發(fā)現(xiàn)NSRunLoop本質(zhì)也是一個(gè)CFRunLoop士鸥,并且其地址與CFRunLoopGetMain()相同,進(jìn)而可以說(shuō)明NSRunLoop是基于CFRunLoopRef的一層OC包裝谆级。

RunLoop與線程的關(guān)系

平時(shí)都是通過(guò)CFRunLoopGetCurrent(),CFRunLoopGetMain();API獲取當(dāng)前線程和主線程烤礁,但是這兩個(gè)函數(shù)具體做了什么?讓我們通過(guò)CFRunLoop源碼來(lái)一探究竟:

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());
}

在調(diào)用CFRunLoopGetCurrent(),CFRunLoopGetMain()函數(shù)時(shí)肥照,函數(shù)內(nèi)部都會(huì)調(diào)用_CFRunLoopGet0(pthread_t t)函數(shù)脚仔,并傳入不同的線程作為參數(shù)∮咭铮可見(jiàn)調(diào)用CFRunLoopGetMain()時(shí)鲤脏,傳入的是主線程,調(diào)用CFRunLoopGetCurrent()時(shí)傳入的是當(dāng)前的線程(子線程或主線程)吕朵。接下來(lái)繼續(xù)看看_CFRunLoopGet0(pthread_t t)函數(shù):

// 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;
}

透過(guò)_CFRunLoopGet0(pthread_t t)源碼凑兰,如果__CFRunLoops不存在,系統(tǒng)就會(huì)利用當(dāng)前的主線程"pthread_main_thread_np()"創(chuàng)建一個(gè)mainLoop边锁,也就是“mainRunLoop”姑食,然后將創(chuàng)建RunLoop的線程作為key,RunLoop作為value添加到一個(gè)全局的字典CFDictionarySetValue中茅坛。最后獲取"pthread_t"線程對(duì)應(yīng)的loop并返回loop音半。如果"pthread_t"不是主線程,用同樣的方法創(chuàng)建一個(gè)新的RunLoop贡蓖,即"newLoop"曹鸠,同樣將"newLoop"存放到字典中然后返回newLoop。所以關(guān)于RunLoop與線程的關(guān)系可以總結(jié)如下:

  • 每條線程都有唯一的一個(gè)與之對(duì)應(yīng)的RunLoop對(duì)象斥铺;
  • RunLoop保存在一個(gè)全局的Dictionary里 ,線程作為key , Runloop作為value彻桃;
  • 線程剛創(chuàng)建時(shí)并沒(méi)有RunLoop對(duì)象, RunLoop會(huì)在第一次獲取它時(shí)創(chuàng)建;
  • RunLogp會(huì)在線程結(jié)束時(shí)銷毀晾蜘;
  • 主線程的RunLoop已經(jīng)自動(dòng)獲取(創(chuàng)建) ,子線程默認(rèn)沒(méi)有開(kāi)啟Runloop邻眷。
RunLoop對(duì)象里面包含哪些信息?

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法中簡(jiǎn)單通過(guò)NSLog(@"%@",[NSRunLoop currentRunLoop]);獲取信息如下:

2018-11-03 00:38:45.865615+0800 RunLoop_SearchTest[64702:13010624] <CFRunLoop 0x6000001f8200 [0x109e9cc80]>{wakeup port = 0x2503, stopped = false, ignoreWakeUps = false, 
current mode = kCFRunLoopDefaultMode,
common modes = <CFBasicHash 0x600000245c40 [0x109e9cc80]>{type = mutable set, count = 2,
entries =>
    0 : <CFString 0x10b20ce88 [0x109e9cc80]>{contents = "UITrackingRunLoopMode"}
    2 : <CFString 0x109e72818 [0x109e9cc80]>{contents = "kCFRunLoopDefaultMode"}
}
,
common mode items = <CFBasicHash 0x600000245f10 [0x109e9cc80]>{type = mutable set, count = 16,
entries =>
    0 : <CFRunLoopSource 0x600000167800 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x10ed3e75a)}}
    1 : <CFRunLoopSource 0x604000168040 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x2d03, callout = PurpleEventCallback (0x10ed40bf7)}}
    3 : <CFRunLoopObserver 0x604000139aa0 [0x109e9cc80]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x10a63057f), context = <CFRunLoopObserver context 0x6040000cc940>}
    4 : <CFRunLoopObserver 0x60000013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x10fb70672), context = <CFRunLoopObserver context 0x0>}
    6 : <CFRunLoopObserver 0x60400013a720 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x10a079e7c), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}
    8 : <CFRunLoopObserver 0x60400013a5e0 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (
    0 : <0x7f8c1b008048>
)}}
    9 : <CFRunLoopObserver 0x60400013a540 [0x109e9cc80]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (
    0 : <0x7f8c1b008048>
)}}
    12 : <CFRunLoopObserver 0x60400013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x10a079e01), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}
    13 : <CFRunLoopSource 0x604000168340 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x6040000be960, callout = FBSSerialQueueRunLoopSourceHandler (0x10e4ac82f)}}
    14 : <CFRunLoopSource 0x604000168880 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 43275, subsystem = 0x10b1c3fe8, context = 0x0}}
    15 : <CFRunLoopSource 0x604000168f40 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x604000258600, callout = __handleHIDEventFetcherDrain (0x10a9a7a8e)}}
    16 : <CFRunLoopSource 0x604000169b40 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 42243, subsystem = 0x10b1de668, context = 0x6000002291e0}}
    17 : <CFRunLoopSource 0x604000169540 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 39943, subsystem = 0x10e8bdf78, context = 0x6040000be780}}
    18 : <CFRunLoopSource 0x600000168b80 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x60000044f300> {port = 5527, callback = 0x0}}
    19 : <CFRunLoopSource 0x6000001687c0 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x600000223f80> {port = 3c17, callback = 0x121f79643}}
    20 : <CFRunLoopSource 0x604000168c40 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x604000149b60, callout = __handleEventQueue (0x10a9a7a82)}}
}
,
modes = <CFBasicHash 0x600000245b50 [0x109e9cc80]>{type = mutable set, count = 4,
entries =>
    2 : <CFRunLoopMode 0x600000188200 [0x109e9cc80]>{name = UITrackingRunLoopMode, port set = 0x1b03, queue = 0x600000149ab0, source = 0x6000001882d0 (not fired), timer port = 0x5403, 
    sources0 = <CFBasicHash 0x604000258e10 [0x109e9cc80]>{type = mutable set, count = 4,
entries =>
    0 : <CFRunLoopSource 0x600000167800 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x10ed3e75a)}}
    1 : <CFRunLoopSource 0x604000168c40 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x604000149b60, callout = __handleEventQueue (0x10a9a7a82)}}
    2 : <CFRunLoopSource 0x604000168340 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x6040000be960, callout = FBSSerialQueueRunLoopSourceHandler (0x10e4ac82f)}}
    3 : <CFRunLoopSource 0x604000168f40 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x604000258600, callout = __handleHIDEventFetcherDrain (0x10a9a7a8e)}}
}
,
    sources1 = <CFBasicHash 0x604000258d80 [0x109e9cc80]>{type = mutable set, count = 6,
entries =>
    1 : <CFRunLoopSource 0x604000168040 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x2d03, callout = PurpleEventCallback (0x10ed40bf7)}}
    2 : <CFRunLoopSource 0x600000168b80 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x60000044f300> {port = 5527, callback = 0x0}}
    3 : <CFRunLoopSource 0x604000168880 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 43275, subsystem = 0x10b1c3fe8, context = 0x0}}
    4 : <CFRunLoopSource 0x6000001687c0 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x600000223f80> {port = 3c17, callback = 0x121f79643}}
    5 : <CFRunLoopSource 0x604000169b40 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 42243, subsystem = 0x10b1de668, context = 0x6000002291e0}}
    6 : <CFRunLoopSource 0x604000169540 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 39943, subsystem = 0x10e8bdf78, context = 0x6040000be780}}
}
,
    observers = (
    "<CFRunLoopObserver 0x60400013a540 [0x109e9cc80]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7f8c1b008048>\n)}}",
    "<CFRunLoopObserver 0x604000139aa0 [0x109e9cc80]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x10a63057f), context = <CFRunLoopObserver context 0x6040000cc940>}",
    "<CFRunLoopObserver 0x60400013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x10a079e01), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}",
    "<CFRunLoopObserver 0x60000013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x10fb70672), context = <CFRunLoopObserver context 0x0>}",
    "<CFRunLoopObserver 0x60400013a720 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x10a079e7c), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}",
    "<CFRunLoopObserver 0x60400013a5e0 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7f8c1b008048>\n)}}"
),
    timers = (null),
    currently 562869526 (825889558479316) / soft deadline in: 1.84459182e+10 sec (@ -1) / hard deadline in: 1.84459182e+10 sec (@ -1)
},

    3 : <CFRunLoopMode 0x604000188610 [0x109e9cc80]>{name = GSEventReceiveRunLoopMode, port set = 0x5303, queue = 0x604000149e20, source = 0x6040001886e0 (not fired), timer port = 0x2c03, 
    sources0 = <CFBasicHash 0x604000258f00 [0x109e9cc80]>{type = mutable set, count = 1,
entries =>
    0 : <CFRunLoopSource 0x600000167800 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x10ed3e75a)}}
}
,
    sources1 = <CFBasicHash 0x604000258f30 [0x109e9cc80]>{type = mutable set, count = 1,
entries =>
    0 : <CFRunLoopSource 0x604000168100 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x2d03, callout = PurpleEventCallback (0x10ed40bf7)}}
}
,
    observers = (null),
    timers = (null),
    currently 562869526 (825889560343690) / soft deadline in: 1.84459182e+10 sec (@ -1) / hard deadline in: 1.84459182e+10 sec (@ -1)
},

    4 : <CFRunLoopMode 0x600000187c50 [0x109e9cc80]>{name = kCFRunLoopDefaultMode, port set = 0x2403, queue = 0x6000001498a0, source = 0x600000187b80 (not fired), timer port = 0x2303, 
    sources0 = <CFBasicHash 0x604000258ea0 [0x109e9cc80]>{type = mutable set, count = 4,
entries =>
    0 : <CFRunLoopSource 0x600000167800 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x10ed3e75a)}}
    1 : <CFRunLoopSource 0x604000168c40 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x604000149b60, callout = __handleEventQueue (0x10a9a7a82)}}
    2 : <CFRunLoopSource 0x604000168340 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x6040000be960, callout = FBSSerialQueueRunLoopSourceHandler (0x10e4ac82f)}}
    3 : <CFRunLoopSource 0x604000168f40 [0x109e9cc80]>{signalled = Yes, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x604000258600, callout = __handleHIDEventFetcherDrain (0x10a9a7a8e)}}
}
,
    sources1 = <CFBasicHash 0x604000258e70 [0x109e9cc80]>{type = mutable set, count = 6,
entries =>
    1 : <CFRunLoopSource 0x604000168040 [0x109e9cc80]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x2d03, callout = PurpleEventCallback (0x10ed40bf7)}}
    2 : <CFRunLoopSource 0x600000168b80 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x60000044f300> {port = 5527, callback = 0x0}}
    3 : <CFRunLoopSource 0x604000168880 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 43275, subsystem = 0x10b1c3fe8, context = 0x0}}
    4 : <CFRunLoopSource 0x6000001687c0 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <MSHRunLoopSource 0x600000223f80> {port = 3c17, callback = 0x121f79643}}
    5 : <CFRunLoopSource 0x604000169b40 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 42243, subsystem = 0x10b1de668, context = 0x6000002291e0}}
    6 : <CFRunLoopSource 0x604000169540 [0x109e9cc80]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource MIG Server> {port = 39943, subsystem = 0x10e8bdf78, context = 0x6040000be780}}
}
,
    observers = (
    "<CFRunLoopObserver 0x60400013a540 [0x109e9cc80]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7f8c1b008048>\n)}}",
    "<CFRunLoopObserver 0x604000139aa0 [0x109e9cc80]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x10a63057f), context = <CFRunLoopObserver context 0x6040000cc940>}",
    "<CFRunLoopObserver 0x60400013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x10a079e01), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}",
    "<CFRunLoopObserver 0x60000013a360 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x10fb70672), context = <CFRunLoopObserver context 0x0>}",
    "<CFRunLoopObserver 0x60400013a720 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x10a079e7c), context = <CFRunLoopObserver context 0x7f8c1ac00d60>}",
    "<CFRunLoopObserver 0x60400013a5e0 [0x109e9cc80]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x10a04adf2), context = <CFArray 0x604000456950 [0x109e9cc80]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7f8c1b008048>\n)}}"
),
    timers = <CFArray 0x6000000bdee0 [0x109e9cc80]>{type = mutable-small, count = 1, values = (
    0 : <CFRunLoopTimer 0x604000168b80 [0x109e9cc80]>{valid = Yes, firing = No, interval = 0, tolerance = 0, next fire date = 562869525 (-1.36409605 @ 825888200199189), callout = (NSTimer) [_UISystemGestureGateGestureRecognizer _timeOut] (0x108cd348a / 0x10a61169e) (/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/UIKit.framework/UIKit), context = <CFRunLoopTimer context 0x60400043cb40>}
)},
    currently 562869526 (825889560397419) / soft deadline in: 1.84467441e+10 sec (@ 825888200199189) / hard deadline in: 1.84467441e+10 sec (@ 825888200199189)
},

    5 : <CFRunLoopMode 0x604000189720 [0x109e9cc80]>{name = kCFRunLoopCommonModes, port set = 0x4713, queue = 0x60400014a7c0, source = 0x604000189580 (not fired), timer port = 0xa80f, 
    sources0 = (null),
    sources1 = (null),
    observers = (null),
    timers = (null),
    currently 562869526 (825889564441067) / soft deadline in: 1.84459182e+10 sec (@ -1) / hard deadline in: 1.84459182e+10 sec (@ -1)
},


信息量有點(diǎn)多剔交,日志中RunLoop大概包含current mode肆饶、common modes、common mode items岖常、modes這些信息驯镊。實(shí)際上從開(kāi)源的文檔里,RunLoop包含的成員遠(yuǎn)不止上面這些,具體包含內(nèi)容如下圖:

RunLoop結(jié)構(gòu)體成員.png

其中比較重要的是"_modes"這個(gè)成員板惑,它是一個(gè)集合類型橄镜,里面存放了多個(gè)CFRunLoopMode類型的mode成員,一個(gè)RunLoop可以有多個(gè)mode冯乘,這些mode都包含在"_modes"里蛉鹿。CFRunLoopMode結(jié)構(gòu)體如下:

CFRunLoopMode 結(jié)構(gòu)體.png

CFRunLoopModeRef是什么?

  • CFRunLoopModeRef代表RunLoop的運(yùn)行模式往湿;
  • 一個(gè)RunLoop包含若干個(gè)Mode ,每個(gè)Mode又包含若干個(gè)Source0/Source1/Timer/Observer妖异;
  • RunLoop啟動(dòng)時(shí)只能選擇其中一個(gè)Mode ,作為currentMode;
  • 如果需要切換Mode ,只能退出當(dāng)前Loop ,再重新選擇一個(gè)Mode進(jìn)入领追;
  • 不同組的Source0/Source1/Timer/Observer能分隔開(kāi)來(lái),互不影響他膳;
  • 如果Mode里沒(méi)有Source0/Source1/Timer, RunLoop會(huì)立馬退出(很多人說(shuō)沒(méi)有Observer也會(huì)退出,但是我看源碼上面并沒(méi)有對(duì)Observer的存在做任何判斷绒窑,源碼如下:)棕孙。
static Boolean __CFRunLoopModeIsEmpty(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopModeRef previousMode) {
    CHECK_FOR_FORK();
    if (NULL == rlm) return true;
#if DEPLOYMENT_TARGET_WINDOWS
    if (0 != rlm->_msgQMask) return false;
#endif
    Boolean libdispatchQSafe = pthread_main_np() && ((HANDLE_DISPATCH_ON_BASE_INVOCATION_ONLY && NULL == previousMode) || (!HANDLE_DISPATCH_ON_BASE_INVOCATION_ONLY && 0 == _CFGetTSD(__CFTSDKeyIsInGCDMainQ)));
    if (libdispatchQSafe && (CFRunLoopGetMain() == rl) && CFSetContainsValue(rl->_commonModes, rlm->_name)) return false; // represents the libdispatch main queue
    //如果沒(méi)有注入sources0 sources1 或timers,就會(huì)退出RunLoop。
    if (NULL != rlm->_sources0 && 0 < CFSetGetCount(rlm->_sources0)) return false;
    if (NULL != rlm->_sources1 && 0 < CFSetGetCount(rlm->_sources1)) return false;
    if (NULL != rlm->_timers && 0 < CFArrayGetCount(rlm->_timers)) return false;
    struct _block_item *item = rl->_blocks_head;
    while (item) {
        struct _block_item *curr = item;
        item = item->_next;
        Boolean doit = false;
        if (CFStringGetTypeID() == CFGetTypeID(curr->_mode)) {
            doit = CFEqual(curr->_mode, rlm->_name) || (CFEqual(curr->_mode, kCFRunLoopCommonModes) && CFSetContainsValue(rl->_commonModes, rlm->_name));
        } else {
            doit = CFSetContainsValue((CFSetRef)curr->_mode, rlm->_name) || (CFSetContainsValue((CFSetRef)curr->_mode, kCFRunLoopCommonModes) && CFSetContainsValue(rl->_commonModes, rlm->_name));
        }
        if (doit) return false;
    }
    return true;
}

中間三段“return false些膨;”的判斷清晰地說(shuō)明了runloop退出的條件蟀俊。
if (NULL != rlm->_sources0 && 0 < CFSetGetCount(rlm->_sources0)) return false;
if (NULL != rlm->_sources1 && 0 < CFSetGetCount(rlm->_sources1)) return false;
if (NULL != rlm->_timers && 0 < CFArrayGetCount(rlm->_timers)) return false;

RunLoop與mode關(guān)系.png

RunLoop常見(jiàn)的兩種Mode

  • kCFRunLoopDefaultMode ( NSDefaultRunLoopMode) : App默認(rèn)的Mode , 通常主線程會(huì)在這個(gè)模式下運(yùn)行。
  • UITrackingRunLoopMode : 界面跟蹤Mode , 用于 ScrollView 追蹤界面滑動(dòng)事件,保證界面滑動(dòng)不受其他mode的影響订雾。

每一種mode里面都有source0肢预、source1、observers洼哎、timers烫映,他們主要負(fù)責(zé)的內(nèi)容如下:

Source0

  • 觸摸事件處理
  • performSelector:onThread:

Source1

  • 基于Port的線程間通信
  • 系統(tǒng)事件捕捉

Timers

  • NSTimer
  • performSelector:withobiect:afterDelay;

Observers

  • 用于監(jiān)聽(tīng)Runloop的狀態(tài)
  • UI刷新( BeforeWaiting)
  • Autorelease pool ( BeforeWaiting )

兩種方式監(jiān)聽(tīng)RunLoop狀態(tài):

方式①:
- (void)viewDidLoad {
    
    [super viewDidLoad];
    // 創(chuàng)建Observer
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        
        CFRunLoopMode mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent());
        switch (activity) {
            case kCFRunLoopEntry: {
                NSLog(@"kCFRunLoopEntry - %@", mode);
                CFRelease(mode);
                break;
            }
            case kCFRunLoopBeforeTimers:{
                NSLog(@"kCFRunLoopBeforeTimers - %@", mode);
                  CFRelease(mode);
                break;
            }
            case kCFRunLoopBeforeSources:{
                NSLog(@"kCFRunLoopBeforeSources - %@", mode);
                  CFRelease(mode);
                break;
            }
            case kCFRunLoopBeforeWaiting:{
                NSLog(@"kCFRunLoopBeforeWaiting - %@", mode);
                  CFRelease(mode);
                break;
            }
            case kCFRunLoopAfterWaiting:{
                NSLog(@"kCFRunLoopAfterWaiting - %@", mode);
                  CFRelease(mode);
                break;
            }
            case kCFRunLoopExit: {
                NSLog(@"kCFRunLoopExit - %@", mode);
                CFRelease(mode);
                break;
            }
                
            default:
                break;
        }
    });
    // 添加Observer到RunLoop中
    CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
    // 釋放
    CFRelease(observer);
}


方式②:
void observeRunLoopActicities(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
{
    CFRunLoopMode mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent());
    switch (activity) {
        case kCFRunLoopEntry:
             NSLog(@"kCFRunLoopEntry - %@", mode);
            break;
        case kCFRunLoopBeforeTimers:
             NSLog(@"kCFRunLoopBeforeTimers - %@", mode);
            break;
        case kCFRunLoopBeforeSources:
             NSLog(@"kCFRunLoopBeforeSources - %@", mode);
            break;
        case kCFRunLoopBeforeWaiting:
             NSLog(@"kCFRunLoopBeforeWaiting - %@", mode);
            break;
        case kCFRunLoopAfterWaiting:
             NSLog(@"kCFRunLoopAfterWaiting - %@", mode);
            break;
        case kCFRunLoopExit:
             NSLog(@"kCFRunLoopExit - %@", mode);
            break;
        default:
            break;
    }
     CFRelease(mode);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // kCFRunLoopCommonModes默認(rèn)包括kCFRunLoopDefaultMode、UITrackingRunLoopMode
    
    // 創(chuàng)建Observer
    CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, observeRunLoopActicities, NULL);
    // 添加Observer到RunLoop中
    CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
    // 釋放
    CFRelease(observer);
}

RunLoop運(yùn)行邏輯

RunLoop的運(yùn)行邏輯是怎么樣的噩峦?讓我們從一次熟悉的觸摸事件開(kāi)始分析吧O(∩_∩)O~~

觸摸事件函數(shù)調(diào)用棧信息.png

為方便查看- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event調(diào)用的堆棧信息锭沟,特意將堆棧信息提取出來(lái):

(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x000000010401968d RunLoop_SearchTest`-[ViewController touchesBegan:withEvent:](self=0x00007faa9ee66310, _cmd="touchesBegan:withEvent:", touches=1 element, event=0x000060000010dd10) at ViewController.m:28
    frame #1: 0x00000001059307c7 UIKit`forwardTouchMethod + 340
    frame #2: 0x0000000105930662 UIKit`-[UIResponder touchesBegan:withEvent:] + 49
    frame #3: 0x0000000105778e7a UIKit`-[UIWindow _sendTouchesForEvent:] + 2052
    frame #4: 0x000000010577a821 UIKit`-[UIWindow sendEvent:] + 4086
    frame #5: 0x000000010571e370 UIKit`-[UIApplication sendEvent:] + 352
    frame #6: 0x000000012211fe6b UIKit`-[UIApplicationAccessibility sendEvent:] + 85
    frame #7: 0x000000010605f57f UIKit`__dispatchPreprocessedEventFromEventQueue + 2796
    frame #8: 0x0000000106062194 UIKit`__handleEventQueueInternal + 5949
    frame #9: 0x0000000105228bb1 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    frame #10: 0x000000010520d4af CoreFoundation`__CFRunLoopDoSources0 + 271
    frame #11: 0x000000010520ca6f CoreFoundation`__CFRunLoopRun + 1263
    frame #12: 0x000000010520c30b CoreFoundation`CFRunLoopRunSpecific + 635
    frame #13: 0x000000010a3f1a73 GraphicsServices`GSEventRunModal + 62
    frame #14: 0x00000001057030b7 UIKit`UIApplicationMain + 159
    frame #15: 0x000000010401977f RunLoop_SearchTest`main(argc=1, argv=0x00007ffeebbe5fc8) at main.m:15
    frame #16: 0x0000000108cdf955 libdyld.dylib`start + 1
    frame #17: 0x0000000108cdf955 libdyld.dylib`start + 1

從后往前看:frame#17、frame#16是系統(tǒng)的動(dòng)態(tài)庫(kù)加載過(guò)程识补;
frame#15開(kāi)始進(jìn)入應(yīng)用的main.m文件族淮,指向了Line 15,也就是return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));,也就是創(chuàng)建了一個(gè)主運(yùn)行循環(huán)凭涂,讓程序保持運(yùn)行狀態(tài)不退出祝辣。從frame #12開(kāi)始進(jìn)入了RunLoop的入口,也就是CoreFoundation框架下的CFRunLoopRunSpecific函數(shù)导盅,定位到CFRunLoop源碼中:

CFRunLoopRunSpecific函數(shù).png

提取出紅色區(qū)域最關(guān)鍵的三行代碼(也是CFRunLoopRunSpecific函數(shù)的核心):

__CFRunLoopDoObservers(rl, currentMode, kCFRunLoopEntry);
result = __CFRunLoopRun(rl, currentMode, seconds, returnAfterSourceHandled, previousMode);
__CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
也就是說(shuō)一開(kāi)始通知Observers進(jìn)入Loop较幌;
中間RunLoop都是在不停地run;
最后通知Observers退出Loop揍瑟。
顯然最重要的就是中間的過(guò)程②白翻,也就是__CFRunLoopRun函數(shù)。我們繼續(xù)往這個(gè)函數(shù)里面看:
CFRunLoop.c源碼中,從2331~2647行都是這個(gè)函數(shù)的實(shí)現(xiàn)部分滤馍,實(shí)在太長(zhǎng)了岛琼。。巢株。(鑒于函數(shù)里做了大量的平臺(tái)判斷槐瑞,刪除Windows平臺(tái)和無(wú)關(guān)條件代碼后,其實(shí)也就200行吧:)阁苞,等下將精簡(jiǎn)版放出來(lái)困檩,別扔雞蛋就OK)

/* rl, rlm are locked on entrance and exit */
static int32_t __CFRunLoopRun(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFTimeInterval seconds, Boolean stopAfterHandle, CFRunLoopModeRef previousMode) {

    Boolean didDispatchPortLastTime = true;
    int32_t retVal = 0;
    do {
        voucher_mach_msg_state_t voucherState = VOUCHER_MACH_MSG_STATE_UNCHANGED;
        voucher_t voucherCopy = NULL;

        uint8_t msg_buffer[3 * 1024];

        mach_msg_header_t *msg = NULL;
        mach_port_t livePort = MACH_PORT_NULL;

        __CFPortSet waitSet = rlm->_portSet;

        __CFRunLoopUnsetIgnoreWakeUps(rl);
//        通知Observers,即將處理Timers
        if (rlm->_observerMask & kCFRunLoopBeforeTimers) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeTimers);
//        通知Observers,即將處理Sources
        if (rlm->_observerMask & kCFRunLoopBeforeSources) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeSources);
//       處理block
        __CFRunLoopDoBlocks(rl, rlm);
//       處理source0事件
        Boolean sourceHandledThisLoop = __CFRunLoopDoSources0(rl, rlm, stopAfterHandle);
        if (sourceHandledThisLoop) {
            //如果條件成立會(huì)再一次處理block事件
            __CFRunLoopDoBlocks(rl, rlm);
    }

        Boolean poll = sourceHandledThisLoop || (0ULL == timeout_context->termTSR);

        if (MACH_PORT_NULL != dispatchPort && !didDispatchPortLastTime) {

            msg = (mach_msg_header_t *)msg_buffer;
            //涉及到Port,也就是Source1,如果存在Source1事件那槽,就跳轉(zhuǎn)到“handle_msg”代碼塊
            if (__CFRunLoopServiceMachPort(dispatchPort, &msg, sizeof(msg_buffer), &livePort, 0, &voucherState, NULL)) {
                goto handle_msg;
            }
        }

        didDispatchPortLastTime = false;
    //通知Observers開(kāi)始休眠
    if (!poll && (rlm->_observerMask & kCFRunLoopBeforeWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeWaiting);
    __CFRunLoopSetSleeping(rl);
    // do not do any user callouts after this point (after notifying of sleeping)

        // Must push the local-to-this-activation ports in on every loop
        // iteration, as this mode could be run re-entrantly and we don't
        // want these ports to get serviced.

        __CFPortSetInsert(dispatchPort, waitSet);
        
        __CFRunLoopModeUnlock(rlm);
        __CFRunLoopUnlock(rl);

        CFAbsoluteTime sleepStart = poll ? 0.0 : CFAbsoluteTimeGetCurrent();

        //等待別的消息來(lái)喚醒線程
        __CFRunLoopServiceMachPort(waitSet, &msg, sizeof(msg_buffer), &livePort, poll ? 0 : TIMEOUT_INFINITY, &voucherState, &voucherCopy);
        
        
        __CFRunLoopLock(rl);
        __CFRunLoopModeLock(rlm);

        rl->_sleepTime += (poll ? 0.0 : (CFAbsoluteTimeGetCurrent() - sleepStart));

        // Must remove the local-to-this-activation ports in on every loop
        // iteration, as this mode could be run re-entrantly and we don't
        // want these ports to get serviced. Also, we don't want them left
        // in there if this function returns.

        __CFPortSetRemove(dispatchPort, waitSet);
        
        __CFRunLoopSetIgnoreWakeUps(rl);

        // user callouts now OK again
        __CFRunLoopUnsetSleeping(rl);
    // 通知Observers,線程被喚醒
    if (!poll && (rlm->_observerMask & kCFRunLoopAfterWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopAfterWaiting);

        handle_msg:;
        __CFRunLoopSetIgnoreWakeUps(rl);

        //查看線程是怎么被喚醒的。

        if (MACH_PORT_NULL == livePort) {
            CFRUNLOOP_WAKEUP_FOR_NOTHING();
            // handle nothing
        } else if (livePort == rl->_wakeUpPort) {
            CFRUNLOOP_WAKEUP_FOR_WAKEUP();
            // do nothing on Mac OS
        }

        else if (modeQueuePort != MACH_PORT_NULL && livePort == modeQueuePort) {
            //處理Timer事件
            CFRUNLOOP_WAKEUP_FOR_TIMER();
            if (!__CFRunLoopDoTimers(rl, rlm, mach_absolute_time())) {
                // Re-arm the next timer, because we apparently fired early
                __CFArmNextTimerInMode(rlm, rl);
            }
        }

        else if (rlm->_timerPort != MACH_PORT_NULL && livePort == rlm->_timerPort) {
             //處理Timer事件
            CFRUNLOOP_WAKEUP_FOR_TIMER();
            // On Windows, we have observed an issue where the timer port is set before the time which we requested it to be set. For example, we set the fire time to be TSR 167646765860, but it is actually observed firing at TSR 167646764145, which is 1715 ticks early. The result is that, when __CFRunLoopDoTimers checks to see if any of the run loop timers should be firing, it appears to be 'too early' for the next timer, and no timers are handled.
            // In this case, the timer port has been automatically reset (since it was returned from MsgWaitForMultipleObjectsEx), and if we do not re-arm it, then no timers will ever be serviced again unless something adjusts the timer list (e.g. adding or removing timers). The fix for the issue is to reset the timer here if CFRunLoopDoTimers did not handle a timer itself. 9308754
            if (!__CFRunLoopDoTimers(rl, rlm, mach_absolute_time())) {
                // Re-arm the next timer
                __CFArmNextTimerInMode(rlm, rl);
            }
        }

        else if (livePort == dispatchPort) {
             //處理GCD相關(guān)事件
            CFRUNLOOP_WAKEUP_FOR_DISPATCH();
            __CFRunLoopModeUnlock(rlm);
            __CFRunLoopUnlock(rl);
            _CFSetTSD(__CFTSDKeyIsInGCDMainQ, (void *)6, NULL);

            __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(msg);
            _CFSetTSD(__CFTSDKeyIsInGCDMainQ, (void *)0, NULL);
            __CFRunLoopLock(rl);
            __CFRunLoopModeLock(rlm);
            sourceHandledThisLoop = true;
            didDispatchPortLastTime = true;
        } else {
             //處理Source1事件
            CFRUNLOOP_WAKEUP_FOR_SOURCE();
            
            // If we received a voucher from this mach_msg, then put a copy of the new voucher into TSD. CFMachPortBoost will look in the TSD for the voucher. By using the value in the TSD we tie the CFMachPortBoost to this received mach_msg explicitly without a chance for anything in between the two pieces of code to set the voucher again.
            voucher_t previousVoucher = _CFSetTSD(__CFTSDKeyMachMessageHasVoucher, (void *)voucherCopy, os_release);

            // Despite the name, this works for windows handles as well
            CFRunLoopSourceRef rls = __CFRunLoopModeFindSourceForMachPort(rl, rlm, livePort);
            if (rls) {
                mach_msg_header_t *reply = NULL;
                sourceHandledThisLoop = __CFRunLoopDoSource1(rl, rlm, rls, msg, msg->msgh_size, &reply) || sourceHandledThisLoop;
                if (NULL != reply) {
                    (void)mach_msg(reply, MACH_SEND_MSG, reply->msgh_size, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
                    CFAllocatorDeallocate(kCFAllocatorSystemDefault, reply);
                }

        }
            
            // Restore the previous voucher
            _CFSetTSD(__CFTSDKeyMachMessageHasVoucher, previousVoucher, os_release);
            
        } 

        if (msg && msg != (mach_msg_header_t *)msg_buffer) free(msg);
        //處理block事件
    __CFRunLoopDoBlocks(rl, rlm);
        

    if (sourceHandledThisLoop && stopAfterHandle) {
        retVal = kCFRunLoopRunHandledSource;
        } else if (timeout_context->termTSR < mach_absolute_time()) {
            retVal = kCFRunLoopRunTimedOut;
    } else if (__CFRunLoopIsStopped(rl)) {
            __CFRunLoopUnsetStopped(rl);
        retVal = kCFRunLoopRunStopped;
    } else if (rlm->_stopped) {
        rlm->_stopped = false;
        retVal = kCFRunLoopRunStopped;
    } else if (__CFRunLoopModeIsEmpty(rl, rlm, previousMode)) {
        retVal = kCFRunLoopRunFinished;
    }
        
    voucher_mach_msg_revert(voucherState);
    os_release(voucherCopy);


    } while (0 == retVal);

    if (timeout_timer) {
        dispatch_source_cancel(timeout_timer);
        dispatch_release(timeout_timer);
    } else {
        free(timeout_context);
    }

    return retVal;
}
RunLoop運(yùn)行邏輯.png

RunLoop休眠的實(shí)現(xiàn)
根據(jù)源碼中“ __CFRunLoopRun”函數(shù)的實(shí)現(xiàn)細(xì)節(jié)卫玖,RunLoop在處理完Timers驴一、Observers、Blocks甚牲,會(huì)檢查一遍是否有Source1义郑,如果沒(méi)有的話就會(huì)進(jìn)入休眠狀態(tài)≌筛疲“休眠狀態(tài)”下非驮,App不會(huì)進(jìn)行任何動(dòng)作,這近乎一種‘死亡’狀態(tài)雏赦,看起來(lái)又像是‘卡住了’院尔,但是與while(1){};循環(huán)所表現(xiàn)的不一樣的是,這個(gè)時(shí)候當(dāng)前線程不會(huì)處理任何事情喉誊,也不會(huì)阻塞邀摆,不占用CPU資源。系統(tǒng)能做到這樣伍茄,得益于一個(gè)內(nèi)核層面的API栋盹,即mach_msg(msg, MACH_RCV_MSG|(voucherState ? MACH_RCV_VOUCHER : 0)|MACH_RCV_LARGE|((TIMEOUT_INFINITY != timeout) ? MACH_RCV_TIMEOUT : 0)|MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0)|MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AV), 0, msg->msgh_size, port, timeout, MACH_PORT_NULL);,RunLoop 的核心就是一個(gè) mach_msg() 敷矫,RunLoop 調(diào)用mach_msg()這個(gè)函數(shù)去接收消息例获,如果沒(méi)有別人發(fā)送 port 消息過(guò)來(lái),內(nèi)核會(huì)將線程置于等待狀態(tài)曹仗。

RunLoop休眠的核心原理.png

看到這里榨汤,點(diǎn)個(gè)贊唄??.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市怎茫,隨后出現(xiàn)的幾起案子收壕,更是在濱河造成了極大的恐慌妓灌,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,839評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜜宪,死亡現(xiàn)場(chǎng)離奇詭異虫埂,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)圃验,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門掉伏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人澳窑,你說(shuō)我怎么就攤上這事斧散。” “怎么了摊聋?”我有些...
    開(kāi)封第一講書(shū)人閱讀 153,116評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵颅湘,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我栗精,道長(zhǎng)闯参,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,371評(píng)論 1 279
  • 正文 為了忘掉前任悲立,我火速辦了婚禮鹿寨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘薪夕。我一直安慰自己脚草,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,384評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布原献。 她就那樣靜靜地躺著馏慨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪姑隅。 梳的紋絲不亂的頭發(fā)上写隶,一...
    開(kāi)封第一講書(shū)人閱讀 49,111評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音讲仰,去河邊找鬼慕趴。 笑死,一個(gè)胖子當(dāng)著我的面吹牛鄙陡,可吹牛的內(nèi)容都是我干的冕房。 我是一名探鬼主播,決...
    沈念sama閱讀 38,416評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼趁矾,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼耙册!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起毫捣,我...
    開(kāi)封第一講書(shū)人閱讀 37,053評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤详拙,失蹤者是張志新(化名)和其女友劉穎帝际,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體溪厘,經(jīng)...
    沈念sama閱讀 43,558評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡胡本,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,007評(píng)論 2 325
  • 正文 我和宋清朗相戀三年牌柄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了畸悬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,117評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡珊佣,死狀恐怖蹋宦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情咒锻,我是刑警寧澤冷冗,帶...
    沈念sama閱讀 33,756評(píng)論 4 324
  • 正文 年R本政府宣布,位于F島的核電站惑艇,受9級(jí)特大地震影響蒿辙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜滨巴,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,324評(píng)論 3 307
  • 文/蒙蒙 一思灌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧恭取,春花似錦泰偿、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,315評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至攒发,卻和暖如春调塌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背惠猿。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,539評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工烟阐, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人紊扬。 一個(gè)月前我還...
    沈念sama閱讀 45,578評(píng)論 2 355
  • 正文 我出身青樓蜒茄,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親餐屎。 傳聞我的和親對(duì)象是個(gè)殘疾皇子檀葛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,877評(píng)論 2 345