Runloop

RunLoop 是 iOS開發(fā)中非?;A(chǔ)的一個概念,這篇文章先從基礎(chǔ)例子入手,分析 CFRunLoop 的源碼,介紹 RunLoop 的概念以及底層實(shí)現(xiàn)原理,最后通過檢測卡頓的例子結(jié)束runloop講解

一、runloop最重要的三個函數(shù)

    • (void)run; // 進(jìn)入處理事件循環(huán),如果沒有事件則立刻返回。注意:主線程上調(diào)用這個方法會導(dǎo)致無法返回(進(jìn)入無限循環(huán),雖然不會阻塞主線程),因為主線程一般總是會有事件處理。
    • (void)runUntilDate:(NSDate *)limitDate; //同run方法,增加超時參數(shù)limitDate,避免進(jìn)入無限循環(huán)。使用在UI線程(亦即主線程)上,可以達(dá)到暫停的效果。
    • (BOOL)runMode:(NSString *)mode beforeDate:(NSDate *)limitDate; //等待消息處理,好比在PC終端窗口上等待鍵盤輸入。一旦有合適事件(mode相當(dāng)于定義了事件的類型)被處理了,則立刻返回;類同run方法,如果沒有事件處理也立刻返回;是否事件處理由返回布爾值判斷。同樣limitDate為超時參數(shù)。
- (void)threadWait
{
    stopFlag = NO;
    NSLog(@"Start a new thread");
    [NSThread detachNewThreadSelector:@selector(newThreadProc) toTarget:self withObject:nil];
    while (!stopFlag) {
        NSLog(@"Beginrunloop");
        BOOL finish = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"dealEvent = %@, Endrunloop", finish == YES ? @"YES": @"NO");
    }
    NSLog(@"OK");
}
- (void)newThreadProc
{
    NSLog(@"Enter newThreadProc");
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"In new Threadproc count = %ld", i);
        sleep(1);
    }
//    stopFlag = YES;
    [self performSelectorOnMainThread: @selector(setEnd)
                           withObject: nil
                        waitUntilDone: NO];
    NSLog(@"Exit new ThreadProc");
}
-(void)setEnd{
    stopFlag = YES;
}
2018-01-02 17:33:15.868650+0800 RunloopTest[96462:6747158] Start a new thread
2018-01-02 17:33:15.868855+0800 RunloopTest[96462:6747158] Beginrunloop
2018-01-02 17:33:15.869007+0800 RunloopTest[96462:6747390] Enter newThreadProc
2018-01-02 17:33:15.869118+0800 RunloopTest[96462:6747390] In new Threadproc count = 0
2018-01-02 17:33:15.869855+0800 RunloopTest[96462:6747158] dealEvent = YES, Endrunloop
2018-01-02 17:33:15.869955+0800 RunloopTest[96462:6747158] Beginrunloop
2018-01-02 17:33:15.870145+0800 RunloopTest[96462:6747158] dealEvent = YES, Endrunloop
2018-01-02 17:33:15.870228+0800 RunloopTest[96462:6747158] Beginrunloop
2018-01-02 17:33:16.336256+0800 RunloopTest[96462:6747158] dealEvent = YES, Endrunloop
2018-01-02 17:33:16.336401+0800 RunloopTest[96462:6747158] Beginrunloop
2018-01-02 17:33:16.869622+0800 RunloopTest[96462:6747390] In new Threadproc count = 1
2018-01-02 17:33:17.872758+0800 RunloopTest[96462:6747390] In new Threadproc count = 2
2018-01-02 17:33:18.875654+0800 RunloopTest[96462:6747390] In new Threadproc count = 3
2018-01-02 17:33:19.878071+0800 RunloopTest[96462:6747390] In new Threadproc count = 4
2018-01-02 17:33:20.880257+0800 RunloopTest[96462:6747390] In new Threadproc count = 5
2018-01-02 17:33:21.882079+0800 RunloopTest[96462:6747390] In new Threadproc count = 6
2018-01-02 17:33:22.887392+0800 RunloopTest[96462:6747390] In new Threadproc count = 7
2018-01-02 17:33:23.892905+0800 RunloopTest[96462:6747390] In new Threadproc count = 8
2018-01-02 17:33:24.894575+0800 RunloopTest[96462:6747390] In new Threadproc count = 9
2018-01-02 17:33:25.896342+0800 RunloopTest[96462:6747390] Exit new ThreadProc
2018-01-02 17:33:25.896468+0800 RunloopTest[96462:6747158] dealEvent = YES, Endrunloop
2018-01-02 17:33:25.896643+0800 RunloopTest[96462:6747158] OK

1、主線程運(yùn)行threadWait,運(yùn)行結(jié)果打印順序如上,運(yùn)行期間界面可正常響應(yīng)事件

2、dealEvent = YES, Endrunloop 打印多次,說明runMode:beforeDate:主線程在此期間多次處理事件并返回YES,可以替換成run函數(shù)嘗試,發(fā)現(xiàn)Endrunloop不再打印,后續(xù)操作都被阻斷不會執(zhí)行

3、直接設(shè)置stopFlag=YES 和 通過performSelectorOnMainThread設(shè)置,觀察最后OK打印的時間是有時間差的

- (void)threadTest
{
    _hlThread = [[NSThread alloc] initWithTarget:self selector:@selector(subThreadEntryPoint) object:nil];
    [_hlThread start];
}
- (void)subThreadEntryPoint
{
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
    NSLog(@"啟動Runloop前--%@", runLoop.currentMode);
    [runLoop run];
}
- (void)subThreadOpetion
{
    NSLog(@"啟動Runloop后--%@", [NSRunLoop currentRunLoop].currentMode);
    NSLog(@"%@----子線程任務(wù)開始",[NSThread currentThread]);
    [NSThread sleepForTimeInterval:3.0];
    NSLog(@"%@----子線程任務(wù)結(jié)束",[NSThread currentThread]);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self performSelector:@selector(subThreadOpetion) onThread:_hlThread withObject:nil waitUntilDone:NO];
}
2018-01-02 18:00:50.956511+0800 RunloopTest[97108:6795019] 啟動Runloop前--(null)
2018-01-02 18:00:54.427331+0800 RunloopTest[97108:6795019] 啟動Runloop后--kCFRunLoopDefaultMode
2018-01-02 18:00:54.427727+0800 RunloopTest[97108:6795019] <NSThread: 0x60c0000767c0>{number = 3, name = (null)}----子線程任務(wù)開始
2018-01-02 18:00:57.433010+0800 RunloopTest[97108:6795019] <NSThread: 0x60c0000767c0>{number = 3, name = (null)}----子線程任務(wù)結(jié)束
2018-01-02 18:00:57.433374+0800 RunloopTest[97108:6795019] 啟動Runloop后--kCFRunLoopDefaultMode
2018-01-02 18:00:57.433650+0800 RunloopTest[97108:6795019] <NSThread: 0x60c0000767c0>{number = 3, name = (null)}----子線程任務(wù)開始
2018-01-02 18:01:00.438874+0800 RunloopTest[97108:6795019] <NSThread: 0x60c0000767c0>{number = 3, name = (null)}----子線程任務(wù)結(jié)束

1、主線程調(diào)用threadTest后,打印"啟動Runloop前",之后進(jìn)入等待期間可以接受任何事件,touch屏幕會執(zhí)行“啟動Runloop后”,后續(xù)都執(zhí)行完成以后繼續(xù)等待...

2、子線程一直在運(yùn)行,不會結(jié)束,可以替換run為另外兩個函數(shù),嘗試結(jié)果

二、runloop的概念

RunLoop 實(shí)際上就是一個對象,這個對象管理了其需要處理的事件和消息,并提供了一個入口函數(shù)來執(zhí)行事件循環(huán)的邏輯(即:run系列)。線程執(zhí)行了這個函數(shù)后,就會一直處于這個函數(shù)內(nèi)部 "接受消息->等待->處理" 的循環(huán)中,直到這個循環(huán)結(jié)束(比如傳入 quit 的消息),函數(shù)返回。

iOS 系統(tǒng)中,提供了兩個這樣的對象:NSRunLoop 和 CFRunLoopRef

三、runloop的內(nèi)部邏輯

/// 用DefaultMode啟動
void CFRunLoopRun(void) {
    CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
}
  
/// 用指定的Mode啟動,允許設(shè)置RunLoop超時時間
int CFRunLoopRunInMode(CFStringRef modeName, CFTimeInterval seconds, Boolean stopAfterHandle) {
    return CFRunLoopRunSpecific(CFRunLoopGetCurrent(), modeName, seconds, returnAfterSourceHandled);
}
  
/// RunLoop的實(shí)現(xiàn)
int CFRunLoopRunSpecific(runloop, modeName, seconds, stopAfterHandle) {
     
    /// 首先根據(jù)modeName找到對應(yīng)mode
    CFRunLoopModeRef currentMode = __CFRunLoopFindMode(runloop, modeName, false);
    /// 如果mode里沒有source/timer/observer, 直接返回。
    if (__CFRunLoopModeIsEmpty(currentMode)) return;
     
    /// 1. 通知 Observers: RunLoop 即將進(jìn)入 loop。
    __CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopEntry);
     
    /// 內(nèi)部函數(shù),進(jìn)入loop
    __CFRunLoopRun(runloop, currentMode, seconds, returnAfterSourceHandled) {
         
        Boolean sourceHandledThisLoop = NO;
        int retVal = 0;
        do {
  
            /// 2. 通知 Observers: RunLoop 即將觸發(fā) Timer 回調(diào)。
            __CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeTimers);
            /// 3. 通知 Observers: RunLoop 即將觸發(fā) Source0 (非port) 回調(diào)。
            __CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeSources);
            /// 執(zhí)行被加入的block
            __CFRunLoopDoBlocks(runloop, currentMode);
             
            /// 4. RunLoop 觸發(fā) Source0 (非port) 回調(diào)。
            sourceHandledThisLoop = __CFRunLoopDoSources0(runloop, currentMode, stopAfterHandle);
            /// 執(zhí)行被加入的block
            __CFRunLoopDoBlocks(runloop, currentMode);
  
            /// 5. 如果有 Source1 (基于port) 處于 ready 狀態(tài),直接處理這個 Source1 然后跳轉(zhuǎn)去處理消息。
            if (__Source0DidDispatchPortLastTime) {
                Boolean hasMsg = __CFRunLoopServiceMachPort(dispatchPort, &msg)
                if (hasMsg) goto handle_msg;
            }
             
            /// 通知 Observers: RunLoop 的線程即將進(jìn)入休眠(sleep)。
            if (!sourceHandledThisLoop) {
                __CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeWaiting);
            }
             
            /// 7. 調(diào)用 mach_msg 等待接受 mach_port 的消息。線程將進(jìn)入休眠, 直到被下面某一個事件喚醒。
            /// ? 一個基于 port 的Source 的事件。
            /// ? 一個 Timer 到時間了
            /// ? RunLoop 自身的超時時間到了
            /// ? 被其他什么調(diào)用者手動喚醒
            __CFRunLoopServiceMachPort(waitSet, &msg, sizeof(msg_buffer), &livePort) {
                mach_msg(msg, MACH_RCV_MSG, port); // thread wait for receive msg
            }
  
            /// 8. 通知 Observers: RunLoop 的線程剛剛被喚醒了。
            __CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopAfterWaiting);
             
            /// 收到消息,處理消息。
            handle_msg:
  
            /// 9.1 如果一個 Timer 到時間了,觸發(fā)這個Timer的回調(diào)。
            if (msg_is_timer) {
                __CFRunLoopDoTimers(runloop, currentMode, mach_absolute_time())
            } 
  
            /// 9.2 如果有dispatch到main_queue的block,執(zhí)行block。
            else if (msg_is_dispatch) {
                __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(msg);
            } 
  
            /// 9.3 如果一個 Source1 (基于port) 發(fā)出事件了,處理這個事件
            else {
                CFRunLoopSourceRef source1 = __CFRunLoopModeFindSourceForMachPort(runloop, currentMode, livePort);
                sourceHandledThisLoop = __CFRunLoopDoSource1(runloop, currentMode, source1, msg);
                if (sourceHandledThisLoop) {
                    mach_msg(reply, MACH_SEND_MSG, reply);
                }
            }
             
            /// 執(zhí)行加入到Loop的block
            __CFRunLoopDoBlocks(runloop, currentMode);
             
  
            if (sourceHandledThisLoop && stopAfterHandle) {
                /// 進(jìn)入loop時參數(shù)說處理完事件就返回。
                retVal = kCFRunLoopRunHandledSource;
            } else if (timeout) {
                /// 超出傳入?yún)?shù)標(biāo)記的超時時間了
                retVal = kCFRunLoopRunTimedOut;
            } else if (__CFRunLoopIsStopped(runloop)) {
                /// 被外部調(diào)用者強(qiáng)制停止了
                retVal = kCFRunLoopRunStopped;
            } else if (__CFRunLoopModeIsEmpty(runloop, currentMode)) {
                /// source/timer/observer一個都沒有了
                retVal = kCFRunLoopRunFinished;
            }
             
            /// 如果沒超時,mode里沒空,loop也沒被停止,那繼續(xù)loop。
        } while (retVal == 0);
    }
     
    /// 10. 通知 Observers: RunLoop 即將退出。
    __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
}

可以看到,實(shí)際上 RunLoop 就是這樣一個函數(shù),其內(nèi)部是一個 do-while 循環(huán)。當(dāng)你調(diào)用 CFRunLoopRun() 時,線程就會一直停留在這個循環(huán)里;直到超時或被手動停止,該函數(shù)才會返回

CFRunLoopMode 和 CFRunLoop 的結(jié)構(gòu)大致如下:

struct __CFRunLoopMode {
    CFStringRef _name;            // Mode Name, 例如 @"kCFRunLoopDefaultMode"
    CFMutableSetRef _sources0;    // Set
    CFMutableSetRef _sources1;    // Set
    CFMutableArrayRef _observers; // Array
    CFMutableArrayRef _timers;    // Array
    ...
};
  
struct __CFRunLoop {
    CFMutableSetRef _commonModes;     // Set
    CFMutableSetRef _commonModeItems; // Set
    CFRunLoopModeRef _currentMode;    // Current Runloop Mode
    CFMutableSetRef _modes;           // Set
    ...
};

Source/Timer/Observer 被統(tǒng)稱為 mode item,如果一個 mode 中一個 item 都沒有,則 RunLoop 會直接退出,不進(jìn)入循環(huán)。

關(guān)于source有兩個版本:Source0 和 Source1

  • Source0 只包含了一個回調(diào)(函數(shù)指針),它并不能主動觸發(fā)事件。使用時,你需要先調(diào)用 CFRunLoopSourceSignal(source),將這個 Source 標(biāo)記為待處理,然后手動調(diào)用 CFRunLoopWakeUp(runloop) 來喚醒 RunLoop,讓其處理這個事件。
  • Source1 包含了一個 mach_port 和一個回調(diào)(函數(shù)指針),被用于通過內(nèi)核和其他線程相互發(fā)送消息。這種 Source 能主動喚醒 RunLoop 的線程。如上面例子中的machport

四、利用runloop檢測主線程卡頓

1、針對主線程建立runloop的observer

CFRunLoopObserverContext *context = {0, NULL, NULL, NULL};
CFRunLoopObserverRef runloopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &monitorFunction, context);
CFRunLoopAddObserver(CFRunLoopGetMain(), runloopObserver, kCFRunLoopCommonModes);

2、runloop的observer函數(shù)中檢測狀態(tài)機(jī)的變化,并通知給監(jiān)測者

dispatch_semaphore_t semaphore = [MonitorController shareInstance].semaphore;
[MonitorController shareInstance].activity = activity;
dispatch_semaphore_signal(semaphore);

3、根據(jù)定義的卡頓時間,判斷處理事件時是否卡頓

 _semaphore = dispatch_semaphore_create(0);
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (YES) {
            long waitTime = dispatch_semaphore_wait(_semaphore, dispatch_time(DISPATCH_TIME_NOW, 2000*NSEC_PER_MSEC));
            if(waitTime != 0)
            {
                if(_activity == kCFRunLoopBeforeSources || _activity == kCFRunLoopAfterWaiting)
                {
                    NSLog(@"發(fā)生卡頓");
                    [self logTrace];
                }
            }
        }
    });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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