其他分享
首页 > 其他分享> > Runloop知识梳理

Runloop知识梳理

作者:互联网

Runloop知识梳理

1、NSTimer

NSTimer *timer = [[NSTimer alloc] init];
timer.tolerance = 1.0;

2、autoreleasePool

3、Runloop

typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoop * CFRunLoopRef;
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoopSource * CFRunLoopSourceRef;
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoopObserver * CFRunLoopObserverRef;
typedef struct CF_BRIDGED_MUTABLE_TYPE(NSTimer) __CFRunLoopTimer * CFRunLoopTimerRef;
__CFRunloopMode并未对外暴漏

a、***__CFRunloop***:由pthread线程对象、modes(多个运行模式)、currentMode(当前模式类型)、commonModes(多个运行模式的字符串名称)和commonModeItems(source、timer、observer组成)等组合而成。

/**
*    源码结构如下
**/
struct __CFRunLoop {
        CFRuntimeBase _base;
        pthread_mutex_t _lock;/* locked for accessing mode list */
        __CFPort _wakeUpPort;	// used for CFRunLoopWakeUp 
        Boolean _unused;
        volatile _per_run_data *_perRunData; // reset for runs of the runloop
        pthread_t _pthread;//线程对象,与runloop一一对应
        uint32_t _winthread;
        CFMutableSetRef _commonModes;//运行模式的字符串名称集合
        CFMutableSetRef _commonModeItems;//source、timer、obverser
        CFRunLoopModeRef _currentMode;//当前runloop运行模式
        CFMutableSetRef _modes;//多个运行模式集合
        struct _block_item *_blocks_head;
        struct _block_item *_blocks_tail;
        CFAbsoluteTime _runTime;
        CFAbsoluteTime _sleepTime;
        CFTypeRef _counterpart;
};

b、***__CFRunloopMode***:由source0、source1、timers、observers等组成

//源码结构
struct __CFRunLoopMode {
        CFRuntimeBase _base;
        pthread_mutex_t _lock;	/* must have the run loop locked before locking this */
        CFStringRef _name;
        Boolean _stopped;
        char _padding[3];
        CFMutableSetRef _sources0;
        CFMutableSetRef _sources1;
        CFMutableArrayRef _observers;
        CFMutableArrayRef _timers;
        CFMutableDictionaryRef _portToV1SourceMap;
        __CFPortSet _portSet;
        CFIndex _observerMask;
#if USE_DISPATCH_SOURCE_FOR_TIMERS
        dispatch_source_t _timerSource;
        dispatch_queue_t _queue;
        Boolean _timerFired; // set to true by the source when a timer has fired
        Boolean _dispatchTimerArmed;
#endif
#if USE_MK_TIMER_TOO
        mach_port_t _timerPort;
        Boolean _mkTimerArmed;
#endif
#if DEPLOYMENT_TARGET_WINDOWS
        DWORD _msgQMask;
        void (*_msgPump)(void);
#endif
        uint64_t _timerSoftDeadline; /* TSR */
        uint64_t _timerHardDeadline; /* TSR */
};

c、***__CFRunloopSource***:分source0和source1两种;source0非基于port的,即用户触发的事件,需要手动唤醒线程,将当前线程由内核态切换到用户态;source1基于port的,监听系统端口与通过内核和其他线程发送的消息,能主动唤醒runloop,接收分发系统事件。

//源码结构如下
struct __CFRunLoopSource {
        CFRuntimeBase _base;
        uint32_t _bits;
        pthread_mutex_t _lock;
        CFIndex _order;			/* immutable */
        CFMutableBagRef _runLoops;
        union {
	       CFRunLoopSourceContext version0;	/* immutable, except invalidation */
           CFRunLoopSourceContext1 version1;	/* immutable, except invalidation */
        } _context;
};

d、***__CFRunloopTimer***:基于时间的触发器,基本说的是NSTimer。在预设的时间点唤醒runloop执行回调(因为它是基于runloop,因此它不是实时的,因为runloop只负责分发源消息,如果当前线程在执行复杂的任务,就会延迟执行timer回调,甚至会跳过当前时间点的回调事件)

//源码结构如下
struct __CFRunLoopTimer {
        CFRuntimeBase _base;
        uint16_t _bits;
        pthread_mutex_t _lock;
        CFRunLoopRef _runLoop;
        CFMutableSetRef _rlModes;
        CFAbsoluteTime _nextFireDate;
        CFTimeInterval _interval;		/* immutable */
        CFTimeInterval _tolerance;          /* mutable */
        uint64_t _fireTSR;			/* TSR units */
        CFIndex _order;			/* immutable */
        CFRunLoopTimerCallBack _callout;	/* immutable */
        CFRunLoopTimerContext _context;	/* immutable, except invalidation */
};

e、***__CFRunloopObserver***:监听如下时间点,kRunloopActivity、kRunloopEntry(runloop准备启动)、kRunloopBeforeTimers(runloop即将要处理一些timer相关事件)、kRunloopBeforeSources(runloop即将要处理一些source相关事件)、kRunloopBeforeWaiting(runloop即将进入休眠状态,由用户态切换成内核态)、kRunloopAfterWaiting(runloop被唤醒,由内核态切换成用户态)、kRunloopExit(runloop退出)和kRunloopAllActivities(监听所有状态)

//源码结构如下
struct __CFRunLoopObserver {
        CFRuntimeBase _base;
        pthread_mutex_t _lock;
        CFRunLoopRef _runLoop;
        CFIndex _rlCount;
        CFOptionFlags _activities;		/* immutable */
        CFIndex _order;			/* immutable */
        CFRunLoopObserverCallBack _callout;	/* immutable */
        CFRunLoopObserverContext _context;	/* immutable, except invalidation */
};

4、事件

5、渲染

6、补充

- (NSThread *)networkRequestThread{
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });
    return _networkRequestThread;
}
- (void)networkRequestThreadEntryPoint:(id)__unused object{
    [[NSThread currentThread] setName:@"AFNetworking"];
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
    [runloop run];
}

标签:__,知识,timer,immutable,线程,Runloop,梳理,runloop,事件
来源: https://blog.csdn.net/qqwyuli/article/details/113854760