RunLoop初探
RunLoop是什么
一種do while模型褒搔;
賦予與其關(guān)聯(lián)線程源源不斷處理事務(wù)的能力;
用偽代碼表示如下:
function loop() {
initialize();
do {
var message = get_next_message();
process_message(message);
} while (message != quit);
}
作者:testman00
鏈接:http://www.reibang.com/p/98f3f9f1d171
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
如果不使用RunLoop啟動(dòng)如下程序
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello world.");
}
return 0;
}
輸出:
2017-09-22 09:19:29.380546 Client[37342:3565338] Hello world.
Program ended with exit code: 0
進(jìn)程執(zhí)行完任務(wù)连舍,自動(dòng)退出搬泥,無法做到源源不斷的處理任務(wù)。
如果使用RunLoop啟動(dòng)如下程序
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello world.");
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
NSLog(@"RunLoop will run.");
CFRunLoopRun();
NSLog(@"Program will exit.");
}
return 0;
}
輸出:
2017-09-22 09:24:43.387610 Client[37488:3567968] Hello world.
2017-09-22 09:24:43.390165 Client[37488:3567968] RunLoop will run.
可見進(jìn)程并未退出揍庄,而是在等待消息,處理任務(wù)东抹。
偽代碼存在的問題:過度消耗CUP資源蚂子。RunLoop不存在此問題,可以阻塞當(dāng)前線程(休眠)缭黔,可以喚醒當(dāng)前線程食茎。
RunLoop內(nèi)部數(shù)據(jù)結(jié)構(gòu)

Mode可以理解為RunLoop中不同的通道,RunLoop每次循環(huán)只處理一個(gè)通道中的任務(wù)馏谨。
Source 可以認(rèn)為是系統(tǒng)發(fā)送的事件别渔,如點(diǎn)擊事件。
CFRunLoopSourceRef是事件產(chǎn)生的地方惧互。Source有兩個(gè)版本:Source0 和 Source1钠糊。
Observer可以自己注冊監(jiān)聽RunLoop的生命周期。
示例代碼:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello world.");
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
NSLog(@"RunLoop will run.");
CFRunLoopObserverRef observer =
CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault,
kCFRunLoopExit, true, 0,
^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
NSLog(@"wanna runloop exit...");
});
CFRunLoopAddObserver(runLoop, observer, kCFRunLoopDefaultMode);
dispatch_queue_t queue = dispatch_queue_create("DTAsyncFileDeleterRemoveQueue", 0);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
CFRunLoopStop(runLoop); //exit
});
CFRunLoopRun();
NSLog(@"Program will exit.");
}
return 0;
}
輸出:
2017-09-22 09:52:35.377697 Client[38198:3580524] Hello world.
2017-09-22 09:52:35.378163 Client[38198:3580524] RunLoop will run.
2017-09-22 09:52:37.545909 Client[38198:3580524] wanna runloop exit...
2017-09-22 09:52:37.545952 Client[38198:3580524] Program will exit.
Program ended with exit code: 0
Timer就是我們開發(fā)中用到的定時(shí)器壹哺。
在 CoreFoundation 里面關(guān)于 RunLoop 有5個(gè)類:
CFRunLoopRef
CFRunLoopModeRef
CFRunLoopSourceRef
CFRunLoopTimerRef
CFRunLoopObserverRef
RunLoop的API以及源碼
CFRunLoop位于CoreFoundation層抄伍,是開源的。
- 創(chuàng)建RunLoop
/// 全局的Dictionary管宵,key 是 pthread_t截珍, value 是 CFRunLoopRef
/** 全局字典, 線程對(duì)應(yīng)Runloop,如果沒有值表示是第一次運(yùn)行,創(chuàng)建主線程的RunLoop */
static CFMutableDictionaryRef loopsDic;
/// 訪問 loopsDic 時(shí)的鎖
static CFSpinLock_t loopsLock;
/// 獲取一個(gè) pthread 對(duì)應(yīng)的 RunLoop。
/** get的時(shí)候內(nèi)部自動(dòng)創(chuàng)建一個(gè)runloop, 難怪currentRunLoop時(shí)就有runloop了 */
CFRunLoopRef _CFRunLoopGet(pthread_t thread) {
OSSpinLockLock(&loopsLock);
if (!loopsDic) {
// 第一次進(jìn)入時(shí)箩朴,初始化全局Dic岗喉,并先為主線程創(chuàng)建一個(gè) RunLoop。
loopsDic = CFDictionaryCreateMutable();
CFRunLoopRef mainLoop = _CFRunLoopCreate();
CFDictionarySetValue(loopsDic, pthread_main_thread_np(), mainLoop);
}
/// 直接從 Dictionary 里獲取炸庞。
CFRunLoopRef loop = CFDictionaryGetValue(loopsDic, thread));
if (!loop) {
/// 取不到時(shí)钱床,創(chuàng)建一個(gè)
loop = _CFRunLoopCreate();
CFDictionarySetValue(loopsDic, thread, loop);
/// 注冊一個(gè)回調(diào),當(dāng)線程銷毀時(shí)埠居,順便也銷毀其對(duì)應(yīng)的 RunLoop查牌。
_CFSetTSD(..., thread, loop, __CFFinalizeRunLoop);
}
OSSpinLockUnLock(&loopsLock);
return loop;
}
/** 封裝 獲取 主線程 RunLoop方法 */
CFRunLoopRef CFRunLoopGetMain() {
return _CFRunLoopGet(pthread_main_thread_np());
}
/** 封裝 獲取 當(dāng)前線程 RunLoop方法 */
CFRunLoopRef CFRunLoopGetCurrent() {
return _CFRunLoopGet(pthread_self());
}
作者:testman00
鏈接:http://www.reibang.com/p/98f3f9f1d171
來源:簡書
著作權(quán)歸作者所有事期。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處纸颜。
-
啟動(dòng)RunLoop
image - 喚醒RunLoop
GCD's main queue is a serial queue. So, it can only run a single task at a time. Even if that task runs an inner run loop — for example, runs a modal dialog — then other tasks submitted to the main queue can't run until that has completed.
Tasks submitted using CFRunLoopPerformBlock() can run whenever the run loop is run in one of the target modes. That includes if the run loop is run from within a task that was submitted using CFRunLoopPerformBlock().
Consider the following examples:
CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
printf("outer task milestone 1\n");
CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
printf("inner task\n");
});
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
printf("outer task milestone 2\n");
});
produces output like:
outer task milestone 1
inner task
outer task milestone 2
While this:
dispatch_async(dispatch_get_main_queue(), ^{
printf("outer task milestone 1\n");
dispatch_async(dispatch_get_main_queue(), ^{
printf("inner task\n");
});
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
printf("outer task milestone 2\n");
});
produces:
outer task milestone 1
outer task milestone 2
inner task
- 停止RunLoop
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello world.");
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
dispatch_queue_t queue = dispatch_queue_create("DTAsyncFileDeleterRemoveQueue", 0);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
//不會(huì)喚醒線程
CFRunLoopPerformBlock(runLoop, kCFRunLoopDefaultMode, ^{
NSLog(@"looper run0...");
CFRunLoopStop(runLoop); //exit
});
CFRunLoopWakeUp(runLoop);
});
CFRunLoopRun();
}
return 0;
}
輸出
2017-09-22 13:36:58.345185 Client[42518:3636408] Hello world.
2017-09-22 13:37:00.399378 Client[42518:3636408] looper run0...
Program ended with exit code: 0
- 發(fā)送消息給RunLoop
- timer
- observer
- source
- block
RunLoop Thread dispatch_queue 之間的關(guān)系
dispatch_queue通過RunLoop向線程發(fā)送消息兽泣。消息已block的形式包裝。
RunLoop 使用場景
- CGD
- NSAtuoReleasePool
- UI繪制
- 點(diǎn)擊事件
參考資料
stackoverflow https://stackoverflow.com/questions/12871737/cfrunloopperformblock-vs-dispatch-async/23819286#23819286
蘋果官方文檔
Android:Looper
[TOC]