编程语言
首页 > 编程语言> > Runloop源码

Runloop源码

作者:互联网

源码地址: https://opensource.apple.com/tarballs/CF/
官方文档介绍: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW3

RunLoop图解

RunLoopMode

基本概念

  1. RunLoop: 运行循环,内部实现了一个do while循环用于处理各种事件timer,source0, source1,block
  2. Timer: RooLoop中注册的timer事件,RunLoop

  3. ## CFRunLoopMode
    它代表的是RunLoop当前运行的模式, struct __CFRunLoopMode {
    CFRuntimeBase _base;
    pthread_mutex_t _lock; //用于锁定在特定模式下运行
    CFStringRef _name;
    Boolean _stopped;
    char _padding[3];
    CFMutableSetRef _sources0;
    CFMutableSetRef _sources1;
    CFMutableArrayRef _observers;
    CFMutableArrayRef _timers;
    ..
    };

InputSource

Run Loop Observers

RunLoop定义

struct __CFRunLoop {
    CFRuntimeBase _base; //不负责自动引用计数
    pthread_mutex_t _lock;          /* locked for accessing mode list */
    __CFPort _wakeUpPort;       //RunLoop被唤醒时的port  // used for CFRunLoopWakeUp 
    Boolean _unused;
    volatile _per_run_data *_perRunData; //重制当前RunLoop的状态
    pthread_t _pthread;  //当前RunLoop所运行的线程
    CFMutableSetRef _commonModes;
    CFMutableSetRef _commonModeItems; 
    CFRunLoopModeRef _currentMode;
    CFMutableSetRef _modes;
    struct _block_item *_blocks_head;
    struct _block_item *_blocks_tail;
    CFAbsoluteTime _runTime;
    CFAbsoluteTime _sleepTime;
    CFTypeRef _counterpart;
};

创建RunLoop

- (void)mainThread {
    // The application uses garbage collection, so no autorelease pool is needed.
    NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
 
    // Create a run loop observer and attach it to the run loop.
    CFRunLoopObserverContext  context = {0, self, NULL, NULL, NULL};
    CFRunLoopObserverRef    observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
            kCFRunLoopAllActivities, YES, 0, &myRunLoopObserver, &context);
 
    if (observer)
    {
        CFRunLoopRef    cfLoop = [myRunLoop getCFRunLoop];
        CFRunLoopAddObserver(cfLoop, observer, kCFRunLoopDefaultMode);
    }
 
    // Create and schedule the timer.
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
                selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
 
    NSInteger    loopCount = 10;
    do
    {
        // Run the run loop 10 times to let the timer fire.
        [myRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
        loopCount--;
    }
    while (loopCount);
}

Configuring Run Loop Sources

## TODO: Demo

标签:__,源码,线程,Runloop,pthread,immutable,RunLoop,事件
来源: https://www.cnblogs.com/wwoo/p/runloop-yuan-ma.html