RunLoop初探

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.itdecent.cn/p/98f3f9f1d171
來(lái)源:簡(jiǎn)書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

如果不使用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ú)法做到源源不斷的處理任務(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ù)。

偽代碼存在的問(wèn)題:過(guò)度消耗CUP資源。RunLoop不存在此問(wèn)題,可以阻塞當(dāng)前線程(休眠),可以喚醒當(dāng)前線程。

RunLoop內(nèi)部數(shù)據(jù)結(jié)構(gòu)

image
image

Mode可以理解為RunLoop中不同的通道,RunLoop每次循環(huán)只處理一個(gè)通道中的任務(wù)。
Source 可以認(rèn)為是系統(tǒng)發(fā)送的事件,如點(diǎn)擊事件。

CFRunLoopSourceRef是事件產(chǎn)生的地方。Source有兩個(gè)版本:Source0 和 Source1。

Observer可以自己注冊(cè)監(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,如果沒(méi)有值表示是第一次運(yùn)行,創(chuàng)建主線程的RunLoop */
static CFMutableDictionaryRef loopsDic;
/// 訪問(wèn) 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);
        /// 注冊(cè)一個(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.itdecent.cn/p/98f3f9f1d171
來(lái)源:簡(jiǎn)書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
  • 啟動(dòng)RunLoop


    image
    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通過(guò)RunLoop向線程發(fā)送消息。消息已block的形式包裝。

RunLoop 使用場(chǎng)景

  • CGD
  • NSAtuoReleasePool
  • UI繪制
  • 點(diǎn)擊事件

參考資料

  1. stackoverflow https://stackoverflow.com/questions/12871737/cfrunloopperformblock-vs-dispatch-async/23819286#23819286

  2. 簡(jiǎn)書

  3. 蘋果官方文檔

  4. Android:Looper

[TOC]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容