CFRunLoop的概念及使用

CFRunLoop的概念

簡單來講,CFRunLoop對象負責監控事件輸入源以及對其進行分發管理。CFRunLoop管理的類型一般分爲sources(CFRunLoopSource)、timers(CFRunLoopTimer)和observers(CFRunLoopObserver)三種類型。git

CFRunLoop的使用

1. CFRunLoopSource

CFRunLoopSourceRef是產生事件的地方。Source包括Source0Source1兩個版本。github

Source0:主要由應用程序管理,它並不能主動觸發事件。使用時,你須要先調用 CFRunLoopSourceSignal(source),將這個Source標記爲待處理,而後手動調用CFRunLoopWakeUp(runloop)來喚醒RunLoop,讓其處理這個事件。一般咱們使用的也是Source0事件bash

Source1:主要因爲RunLoopkernel進行管理。包含了一個mach_port和一個回調(函數指針),被用於經過內核和其餘線程相互發送消息。這種Source能主動喚醒RunLoop的線程。async

- (void)cfSource {
    //建立上下文
    CFRunLoopSourceContext context = {};
    context.perform = runLoopSourceCallback;
    context.info = (__bridge void *)self;
    
    //建立source
    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
    CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
    
    //添加source
    CFRunLoopAddSource(runLoop, source, kCFRunLoopCommonModes);
    
    NSLog(@"create source in %@", [NSDate date]);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //執行source相關事件
        CFRunLoopSourceSignal(source);
        CFRunLoopWakeUp(runLoop);
        CFRelease(source);
    });
}

// source回調
static void runLoopSourceCallback(void *info) {
    NSLog(@"reiceive source in %@", [NSDate date]);
}

//執行結果
create source in Wed Mar 25 16:22:08 2020
reiceive source in Wed Mar 25 16:22:11 2020
複製代碼

根據上面的執行結果,可見,對於Source0事件,咱們必須調用CFRunLoopSourceSignal方法去標記爲「待處理」事件,對於CFRunLoopWakeUp能夠根據具體狀況調用,若是當前RunLoop是處於運行狀態,不調用也是OK的,但爲了不當前RunLoop可能處於休眠狀態,最好加上。函數

2. CFRunLoopTimerRef

CFRunLoopTimerRef是基於時間的觸發器。和NSTimer相似,能夠執行一些定時任務。oop

CFRunLoopTimerRef CFRunLoopTimerCreate(CFAllocatorRef allocator, // 用於分配內存,一般使用kCFAllocatorDefault便可
                                       CFAbsoluteTime fireDate,  // 第一次觸發調用的時間
                                       CFTimeInterval interval,  // 回調間隔
                                       CFOptionFlags flags,      // 蘋果備用參數,傳0便可
                                       CFIndex order,            // RunLoop執行事件的優先級,對於Timer是無用的,傳0便可
                                       CFRunLoopTimerCallBack callout, // 回調callback
                                       CFRunLoopTimerContext *context); // 用於與callback聯繫的上下文context
複製代碼
- (void)cfTimer {
    self.timerCount = 0;
    //建立上下文
    CFRunLoopTimerContext context = {};
    context.info = (__bridge void*)self; //將當前對象做爲參數傳入
    
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
                                                   CFAbsoluteTimeGetCurrent() + 1, //第一次回調的時間,則設置爲1s之後
                                                   3, //回調時間間隔
                                                   0, 0, &timerFiredCallback, &context);
    // 設置運行時間偏差範圍
    CFRunLoopTimerSetTolerance(timer, 0.1);
    CFRunLoopAddTimer(runloop, timer, kCFRunLoopCommonModes);
    CFRelease(timer);
    NSLog(@"start timer in %@", [NSDate date]);
}

static void timerFiredCallback(CFRunLoopTimerRef timer, void *info) {
    ViewController *controller = (__bridge ViewController *)info;
    NSLog(@"recieve timer event with count: %@, in %@", @(controller.timerCount), [NSDate date]);
    if (++controller.timerCount == 5) {
        CFRunLoopTimerInvalidate(timer); //關閉定時器
    }
}
複製代碼
//執行結果
start timer in Wed Mar 25 16:42:59 2020
recieve timer event with count: 0, in Wed Mar 25 16:43:00 2020
recieve timer event with count: 1, in Wed Mar 25 16:43:03 2020
recieve timer event with count: 2, in Wed Mar 25 16:43:06 2020
recieve timer event with count: 3, in Wed Mar 25 16:43:09 2020
recieve timer event with count: 4, in Wed Mar 25 16:43:12 2020
複製代碼

根據結果,能夠看到第一次回調是在1s以後,剩餘的回調都是每隔3s回調一次。佈局

3. CFRunLoopObserverRef

CFRunLoopObserverRef:觀察者,主要用於觀察RunLoop的狀態變化,以便在不一樣狀態時作一些操做。能夠經過CFRunLoopObserverCreateWithHandlerCFRunLoopObserverCreate方法建立觀察對象,前者是經過block方式回調,後者是經過C函數callback方式。post

  • 狀態集
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
    kCFRunLoopEntry         = (1UL << 0), // 即將進入Loop
    kCFRunLoopBeforeTimers  = (1UL << 1), // 即將處理 Timer
    kCFRunLoopBeforeSources = (1UL << 2), // 即將處理 Source
    kCFRunLoopBeforeWaiting = (1UL << 5), // 即將進入休眠
    kCFRunLoopAfterWaiting  = (1UL << 6), // 剛從休眠中喚醒
    kCFRunLoopExit          = (1UL << 7), // 即將退出Loop
};
複製代碼
  • 經過監聽RunLoopkCFRunLoopBeforeWaitingkCFRunLoopExit狀態,回調處理相關操做,以實現利用RunLoop空閒狀態時作一些額外的操做。
- (void)runBlockWhenMainThreadIdle {
    __weak typeof(self) wSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"start submit block in %@", [NSDate date]);
        [wSelf runWithBlock:^{
            NSLog(@"finish block when main thread is idle in %@", [NSDate date]);
        }];
    });
}

- (void)runWithBlock:(void(^)(void))block {
    CFRunLoopActivity flag = kCFRunLoopBeforeWaiting | kCFRunLoopExit; //監聽RunLoop即將休眠和退出的狀態
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, flag, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        //回調操做
        if (block) {
            block();
        }
        //移除相關監聽
        CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
        CFRelease(observer);
    });
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
}
複製代碼

第三方庫相關應用場景

1. YYTransaction

經過監聽RunLoop進入休眠和結束前的狀態,來執行佈局更新操做。ui

/// Update layout and selection before runloop sleep/end.
- (void)_commitUpdate {
#if !TARGET_INTERFACE_BUILDER
    _state.needUpdate = YES;
    [[YYTransaction transactionWithTarget:self selector:@selector(_updateIfNeeded)] commit];
#else
    [self _update];
#endif
}
複製代碼
@interface YYTransaction()
@property (nonatomic, strong) id target;
@property (nonatomic, assign) SEL selector;
@end

static NSMutableSet *transactionSet = nil;

static void YYRunLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    if (transactionSet.count == 0) return;
    NSSet *currentSet = transactionSet;
    transactionSet = [NSMutableSet new];
    [currentSet enumerateObjectsUsingBlock:^(YYTransaction *transaction, BOOL *stop) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [transaction.target performSelector:transaction.selector];
#pragma clang diagnostic pop
    }];
}

static void YYTransactionSetup() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        transactionSet = [NSMutableSet new];
        CFRunLoopRef runloop = CFRunLoopGetMain();
        CFRunLoopObserverRef observer;
        
        observer = CFRunLoopObserverCreate(CFAllocatorGetDefault(),
                                           kCFRunLoopBeforeWaiting | kCFRunLoopExit,
                                           true,      // repeat
                                           0xFFFFFF,  // after CATransaction(2000000)
                                           YYRunLoopObserverCallBack, NULL);
        CFRunLoopAddObserver(runloop, observer, kCFRunLoopCommonModes);
        CFRelease(observer);
    });
}


@implementation YYTransaction

+ (YYTransaction *)transactionWithTarget:(id)target selector:(SEL)selector{
    if (!target || !selector) return nil;
    YYTransaction *t = [YYTransaction new];
    t.target = target;
    t.selector = selector;
    return t;
}

- (void)commit {
    if (!_target || !_selector) return;
    YYTransactionSetup();
    [transactionSet addObject:self];
}

- (NSUInteger)hash {
    long v1 = (long)((void *)_selector);
    long v2 = (long)_target;
    return v1 ^ v2;
}

- (BOOL)isEqual:(id)object {
    if (self == object) return YES;
    if (![object isMemberOfClass:self.class]) return NO;
    YYTransaction *other = object;
    return other.selector == _selector && other.target == _target;
}
@end
複製代碼

2. NSThread+Add

爲子線程手動添加自動釋放池。經過監聽RunLoop中的kCFRunLoopEntry狀態,保證執行前插入NSAutoreleasePool,而後經過監聽kCFRunLoopBeforeWaiting | kCFRunLoopExit狀態,保證RunLoop進入睡眠或結束時,釋放相關對象。atom

static NSString *const YYNSThreadAutoleasePoolKey = @"YYNSThreadAutoleasePoolKey";
static NSString *const YYNSThreadAutoleasePoolStackKey = @"YYNSThreadAutoleasePoolStackKey";

static const void *PoolStackRetainCallBack(CFAllocatorRef allocator, const void *value) {
    return value;
}

static void PoolStackReleaseCallBack(CFAllocatorRef allocator, const void *value) {
    CFRelease((CFTypeRef)value);
}


static inline void YYAutoreleasePoolPush() {
    NSMutableDictionary *dic =  [NSThread currentThread].threadDictionary;
    NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
    
    if (!poolStack) {
        /* do not retain pool on push, but release on pop to avoid memory analyze warning */
        CFArrayCallBacks callbacks = {0};
        callbacks.retain = PoolStackRetainCallBack;
        callbacks.release = PoolStackReleaseCallBack;
        poolStack = (id)CFArrayCreateMutable(CFAllocatorGetDefault(), 0, &callbacks);
        dic[YYNSThreadAutoleasePoolStackKey] = poolStack;
        CFRelease(poolStack);
    }
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // create
    [poolStack addObject:pool]; // push
}

static inline void YYAutoreleasePoolPop() {
    NSMutableDictionary *dic =  [NSThread currentThread].threadDictionary;
    NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
    [poolStack removeLastObject]; // pop
}

static void YYRunLoopAutoreleasePoolObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    switch (activity) {
        case kCFRunLoopEntry: {
            YYAutoreleasePoolPush();
        } break;
        case kCFRunLoopBeforeWaiting: {
            YYAutoreleasePoolPop();
            YYAutoreleasePoolPush();
        } break;
        case kCFRunLoopExit: {
            YYAutoreleasePoolPop();
        } break;
        default: break;
    }
}

static void YYRunloopAutoreleasePoolSetup() {
    CFRunLoopRef runloop = CFRunLoopGetCurrent();

    CFRunLoopObserverRef pushObserver;
    pushObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopEntry,
                                           true,         // repeat
                                           -0x7FFFFFFF,  // before other observers
                                           YYRunLoopAutoreleasePoolObserverCallBack, NULL);
    CFRunLoopAddObserver(runloop, pushObserver, kCFRunLoopCommonModes);
    CFRelease(pushObserver);
    
    CFRunLoopObserverRef popObserver;
    popObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopBeforeWaiting | kCFRunLoopExit,
                                          true,        // repeat
                                          0x7FFFFFFF,  // after other observers
                                          YYRunLoopAutoreleasePoolObserverCallBack, NULL);
    CFRunLoopAddObserver(runloop, popObserver, kCFRunLoopCommonModes);
    CFRelease(popObserver);
}

@implementation NSThread (YYAdd)

+ (void)addAutoreleasePoolToCurrentRunloop {
    if ([NSThread isMainThread]) return; // The main thread already has autorelease pool.
    NSThread *thread = [self currentThread];
    if (!thread) return;
    if (thread.threadDictionary[YYNSThreadAutoleasePoolKey]) return; // already added
    YYRunloopAutoreleasePoolSetup();
    thread.threadDictionary[YYNSThreadAutoleasePoolKey] = YYNSThreadAutoleasePoolKey; // mark the state
}

@end
複製代碼

這裏還有一點值得參考的是,releasepool的存儲位置是放在了線程的私有空間threadDictionary中。另外關於子線程中操做是否須要手動進行釋放,能夠參考iOS 各個線程 Autorelease 對象的內存管理。我的以爲加上是比較好的,畢竟官方文檔並無明確說明子線程中是不須要加的。

3. SMLagMonitor

RunLoop調用方法主要集中在kCFRunLoopBeforeSourceskCFRunLoopAfterWaiting狀態之間,能夠經過開闢一個子線程來實時計算兩個狀態之間的耗時,看是否超過某個閾值,從而來判斷主線程的卡頓狀況。

@interface SMLagMonitor() {
    int timeoutCount;
    CFRunLoopObserverRef runLoopObserver;
    @public
    dispatch_semaphore_t dispatchSemaphore;
    CFRunLoopActivity runLoopActivity;
}
@end

@implementation SMLagMonitor

#pragma mark - Interface
+ (instancetype)shareInstance {
    static id instance = nil;
    static dispatch_once_t dispatchOnce;
    dispatch_once(&dispatchOnce, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)beginMonitor {
    self.isMonitoring = YES;
    //監測卡頓
    if (runLoopObserver) {
        return;
    }
    dispatchSemaphore = dispatch_semaphore_create(0); //Dispatch Semaphore保證同步
    //建立一個觀察者
    CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL};
    runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                              kCFRunLoopAllActivities,
                                              YES,
                                              0,
                                              &runLoopObserverCallBack,
                                              &context);
    //將觀察者添加到主線程runloop的common模式下的觀察中
    CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
    
    //建立子線程監控
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //子線程開啓一個持續的loop用來進行監控
        while (YES) {
            long semaphoreWait = dispatch_semaphore_wait(dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, STUCKMONITORRATE * NSEC_PER_MSEC));
            if (semaphoreWait != 0) {
                if (!runLoopObserver) {
                    timeoutCount = 0;
                    dispatchSemaphore = 0;
                    runLoopActivity = 0;
                    return;
                }
                //兩個runloop的狀態,BeforeSources和AfterWaiting這兩個狀態區間時間可以檢測到是否卡頓
                if (runLoopActivity == kCFRunLoopBeforeSources || runLoopActivity == kCFRunLoopAfterWaiting) {
                    //出現三次出結果
                    if (++timeoutCount < 3) {
                        continue;
                    }
// NSLog(@"monitor trigger");
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                        NSString *stackStr = [SMCallStack callStackWithType:SMCallStackTypeMain];
                        SMCallStackModel *model = [[SMCallStackModel alloc] init];
                        model.stackStr = stackStr;
                        model.isStuck = YES;
                        [[[SMLagDB shareInstance] increaseWithStackModel:model] subscribeNext:^(id x) {}];
                    });
                } //end activity
            }// end semaphore wait
            timeoutCount = 0;
        }// end while
    });
    
}

- (void)endMonitor {
    self.isMonitoring = NO;
    [self.cpuMonitorTimer invalidate];
    if (!runLoopObserver) {
        return;
    }
    CFRunLoopRemoveObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
    CFRelease(runLoopObserver);
    runLoopObserver = NULL;
}

#pragma mark - Private

static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
    SMLagMonitor *lagMonitor = (__bridge SMLagMonitor*)info;
    lagMonitor->runLoopActivity = activity;
    
    dispatch_semaphore_t semaphore = lagMonitor->dispatchSemaphore;
    dispatch_semaphore_signal(semaphore);
}

@end
複製代碼

RunLoop系列文章

參考資料

相關文章
相關標籤/搜索