Runloop

2023-01-29  本文已影响0人  e521

1、什么是Runloop?

2、Runloop能做些什么?

3、线程和Runloop有什么关系?

    if (!__CFRunLoops) {
        __CFUnlock(&loopsLock);
      // 创建字典
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
      // 创建主线程
    CFRunLoopRef mainLoop = __CFRunLoopCreate(pthread_main_thread_np());
      // 建立主线程和runloop之间的联系
    CFDictionarySetValue(dict, pthreadPointer(pthread_main_thread_np()), mainLoop);
    if (!OSAtomicCompareAndSwapPtrBarrier(NULL, dict, (void * volatile *)&__CFRunLoops)) {
        CFRelease(dict);
    }

4.Runloop的构成

5.如何启动runloop

启动runlopp的三种方式:

- (void)run NS_SWIFT_UNAVAILABLE_FROM_ASYNC("run cannot be used from async contexts.");

- (void)runUntilDate:(NSDate *)limitDate NS_SWIFT_UNAVAILABLE_FROM_ASYNC("run(until:) cannot be used from async contexts.");

- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate

前两种方式是基于while循环的调用第三种启动方式,前两种方式是一种无限循环。

    public func run() {
        while run(mode: .default, before: Date.distantFuture) { }
    }

    public func run(until limitDate: Date) {
        while run(mode: .default, before: limitDate) && limitDate.timeIntervalSinceReferenceDate > CFAbsoluteTimeGetCurrent() { }
    }

    public func run(mode: RunLoop.Mode, before limitDate: Date) -> Bool {
        if _cfRunLoop !== CFRunLoopGetCurrent() {
            return false
        }
        let modeArg = mode._cfStringUniquingKnown
        if _CFRunLoopFinished(_cfRunLoop, modeArg) {
            return false
        }
        
        let limitTime = limitDate.timeIntervalSinceReferenceDate
        let ti = limitTime - CFAbsoluteTimeGetCurrent()
        CFRunLoopRunInMode(modeArg, ti, true)
        return true
    }

6、Runloop有几种状态

7、主线程需要保活吗?保活的方式有几种?

参考链接:
iOS 线程保活
Runloop
RunLoop从源码到应用全面解析

上一篇下一篇

猜你喜欢

热点阅读