RunLoop 是基礎(chǔ)的一個(gè)概念砸王,在 iOS 里它是由 CFRunLoop 實(shí)現(xiàn)推盛。本章將從源碼的方面梳理下RunLoop相關(guān)的概念、結(jié)構(gòu)谦铃、原理耘成。
淺談RunLoop
RunLoop概念:
一般來(lái)講,一個(gè)線程在執(zhí)行任務(wù)完成后,就會(huì)結(jié)束凿跳。但是在我們的應(yīng)用程序中不會(huì)直接結(jié)束件豌,而是會(huì)在線程中構(gòu)建一個(gè)消息循環(huán)機(jī)制。當(dāng)有事件要去處理時(shí)笨厥龋活線程,當(dāng)沒(méi)有事件要處理時(shí)讓線程進(jìn)入休眠骡显,這個(gè)消息循環(huán)的機(jī)制就是RunLoop疆栏。
RunLoop和線程的關(guān)系:
- RunLoop是基于線程來(lái)管理的,所以是一一對(duì)應(yīng)的關(guān)系
- 主線程中會(huì)自動(dòng)獲取Runloop惫谤,子線程默認(rèn)不會(huì)獲取Runloop
RunLoop創(chuàng)建:
蘋(píng)果不允許直接創(chuàng)建 RunLoop壁顶,它只提供了兩個(gè)自動(dòng)獲取的函數(shù):CFRunLoopGetMain()
和 CFRunLoopGetCurrent()
,這兩個(gè)函數(shù)最終會(huì)調(diào)用以下私有函數(shù)_CFRunLoopGet0()
溜歪。
相關(guān)源碼如下:
static CFMutableDictionaryRef __CFRunLoops = NULL;
static CFLock_t loopsLock = CFLockInit;
// should only be called by Foundation
// t==0 is a synonym for "main thread" that always works
CF_EXPORT CFRunLoopRef _CFRunLoopGet0(pthread_t t) {
if (pthread_equal(t, kNilPthreadT)) {
t = pthread_main_thread_np();
}
__CFLock(&loopsLock);
if (!__CFRunLoops) {
__CFUnlock(&loopsLock);
CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
CFRunLoopRef mainLoop = __CFRunLoopCreate(pthread_main_thread_np());
CFDictionarySetValue(dict, pthreadPointer(pthread_main_thread_np()), mainLoop);
if (!OSAtomicCompareAndSwapPtrBarrier(NULL, dict, (void * volatile *)&__CFRunLoops)) {
CFRelease(dict);
}
CFRelease(mainLoop);
__CFLock(&loopsLock);
}
CFRunLoopRef loop = (CFRunLoopRef)CFDictionaryGetValue(__CFRunLoops, pthreadPointer(t));
__CFUnlock(&loopsLock);
if (!loop) {
CFRunLoopRef newLoop = __CFRunLoopCreate(t);
__CFLock(&loopsLock);
loop = (CFRunLoopRef)CFDictionaryGetValue(__CFRunLoops, pthreadPointer(t));
if (!loop) {
CFDictionarySetValue(__CFRunLoops, pthreadPointer(t), newLoop);
loop = newLoop;
}
// don't release run loops inside the loopsLock, because CFRunLoopDeallocate may end up taking it
__CFUnlock(&loopsLock);
CFRelease(newLoop);
}
if (pthread_equal(t, pthread_self())) {
_CFSetTSD(__CFTSDKeyRunLoop, (void *)loop, NULL);
if (0 == _CFGetTSD(__CFTSDKeyRunLoopCntr)) {
_CFSetTSD(__CFTSDKeyRunLoopCntr, (void *)(PTHREAD_DESTRUCTOR_ITERATIONS-1), (void (*)(void *))__CFFinalizeRunLoop);
}
}
return loop;
}
RunLoop結(jié)構(gòu)
- CFRunLoopRef
- CFRunLoopModeRef
- CFRunLoopSourceRef
- CFRunLoopObserverRef
- CFRunLoopTimerRef
// CFRunLoopModeRef
typedef struct __CFRunLoopMode *CFRunLoopModeRef;
// CFRunLoopRef
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoop * CFRunLoopRef;
// CFRunLoopSourceRef
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoopSource * CFRunLoopSourceRef;
// CFRunLoopObserverRef
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFRunLoopObserver * CFRunLoopObserverRef;
// CFRunLoopTimerRef
typedef struct CF_BRIDGED_MUTABLE_TYPE(NSTimer) __CFRunLoopTimer * CFRunLoopTimerRef;
- CFRunLoopRef
CFRunLoopRef
包含了對(duì)應(yīng)的線程若专,Mode集合,當(dāng)前的Mode等等蝴猪;
// 結(jié)構(gòu)體定義
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 run loop
pthread_t _pthread;
uint32_t _winthread;
CFMutableSetRef _commonModes;
CFMutableSetRef _commonModeItems;
CFRunLoopModeRef _currentMode;
CFMutableSetRef _modes;
struct _block_item *_blocks_head;
struct _block_item *_blocks_tail;
CFAbsoluteTime _runTime;
CFAbsoluteTime _sleepTime;
CFTypeRef _counterpart;
};
- CFRunLoopModeRef
CFRunLoopModeRef
代表著RunLoop的運(yùn)行模式调衰,一個(gè)RunLoop中可以有多個(gè)mode,一個(gè)mode里面又可以有多個(gè)source自阱、observer嚎莉、timer等等。系統(tǒng)五個(gè)Mode:
- kCFRunLoopDefaultMode:App的默認(rèn)Mode沛豌,通常主線程是在這個(gè)Mode下運(yùn)行
- UITrackingRunLoopMode:界面跟蹤 Mode趋箩,用于 ScrollView 追蹤觸摸滑動(dòng),保證界面滑動(dòng)時(shí)不受其他 Mode 影響
- UIInitializationRunLoopMode: 在剛啟動(dòng) App 時(shí)第進(jìn)入的第一個(gè) Mode加派,啟動(dòng)完成后就不再使用
- GSEventReceiveRunLoopMode: 接受系統(tǒng)事件的內(nèi)部 Mode叫确,通常用不到
- kCFRunLoopCommonModes: 這是一個(gè)占位用的Mode,不是一種真正的Mode
// 結(jié)構(gòu)體定義
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 */
};
- CFRunLoopSourceRef
CFRunLoopSourceRef
是產(chǎn)生事件的地方芍锦。Source有兩個(gè)版本:Source0 和 Source1竹勉。
// 結(jié)構(gòu)體定義
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;
};
Source0于Source1的區(qū)別如下:
- Source0 只包含了一個(gè)回調(diào) ,它并不能主動(dòng)觸發(fā)事件
- Source1包含了一個(gè) mach_port和一個(gè)回調(diào) 醉旦,被用于通過(guò)內(nèi)核和其他線程相互發(fā)送消息(系統(tǒng)消息饶米,例如觸摸手勢(shì),屏幕解鎖车胡,按鍵等等)這種Source 能主動(dòng)喚醒RunLoop 的線程
// Source0
typedef struct {
CFIndex version;
void * info;
const void *(*retain)(const void *info);
void (*release)(const void *info);
CFStringRef (*copyDescription)(const void *info);
Boolean (*equal)(const void *info1, const void *info2);
CFHashCode (*hash)(const void *info);
void (*schedule)(void *info, CFRunLoopRef rl, CFRunLoopMode mode);
void (*cancel)(void *info, CFRunLoopRef rl, CFRunLoopMode mode);
void (*perform)(void *info);
} CFRunLoopSourceContext;
// Source1
typedef struct {
CFIndex version;
void * info;
const void *(*retain)(const void *info);
void (*release)(const void *info);
CFStringRef (*copyDescription)(const void *info);
Boolean (*equal)(const void *info1, const void *info2);
CFHashCode (*hash)(const void *info);
#if TARGET_OS_OSX || TARGET_OS_IPHONE
mach_port_t (*getPort)(void *info);
void * (*perform)(void *msg, CFIndex size, CFAllocatorRef allocator, void *info);
#else
void * (*getPort)(void *info);
void (*perform)(void *info);
#endif
} CFRunLoopSourceContext1;
- CFRunLoopObserverRef
CFRunLoopObserverRef
即是RunLoop的Observer檬输,在它的結(jié)構(gòu)體內(nèi)部有一個(gè)_runLoop
成員和回調(diào),每個(gè)Observer只能監(jiān)聽(tīng)一個(gè)RunLoop匈棘,當(dāng) RunLoop 的狀態(tài)發(fā)生變化時(shí)丧慈,Observer就會(huì)被觸發(fā)回調(diào)。RunLoop的六個(gè)狀態(tài)如下:
// 結(jié)構(gòu)體定義
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 */
};
/* Run Loop Observer Activities */
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0), // 進(jìn)入 loop
kCFRunLoopBeforeTimers = (1UL << 1), // 觸發(fā) Timer 回調(diào)
kCFRunLoopBeforeSources = (1UL << 2), // 觸發(fā) Source0 回調(diào)
kCFRunLoopBeforeWaiting = (1UL << 5), // 等待 mach_port 消息
kCFRunLoopAfterWaiting = (1UL << 6), // 接收 mach_port 消息
kCFRunLoopExit = (1UL << 7), // 退出 loop
kCFRunLoopAllActivities = 0x0FFFFFFFU // loop 所有狀態(tài)改變
};
- CFRunLoopTimerRef
CFRunLoopTimerRef
是基于Timer的觸發(fā)器,在它的結(jié)構(gòu)體內(nèi)部有一個(gè)時(shí)間間隔和回調(diào),一個(gè)Timer僅能夠添加到一個(gè)RunLoop中逃默,當(dāng)其加入到 RunLoop 時(shí)鹃愤,RunLoop會(huì)注冊(cè)對(duì)應(yīng)的時(shí)間點(diǎn),當(dāng)時(shí)間間隔到達(dá)后完域,RunLoop
會(huì)被喚醒以執(zhí)行該回調(diào)软吐。
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 */
};
以上這些就是對(duì)RunLoop結(jié)構(gòu)的介紹,下面我將結(jié)合CFRunLoop 的源碼 來(lái)跟分析下 RunLoop 的原理吧吟税。
RunLoop實(shí)現(xiàn)原理
首先凹耙,我將重要的函數(shù)調(diào)用順序依次排開(kāi):
CFRunLoopRun()
->
CFRunLoopRunSpecific()
->
__CFRunLoopRun()
可以參考這個(gè)流程圖
第一步:外層函數(shù)執(zhí)行了do while,為線程后面loop做準(zhǔn)備肠仪。 通知observers肖抱,RunLoop狀態(tài)變化:kCFRunLoopEntry
,RunLoop 要開(kāi)始進(jìn)入循環(huán)了异旧;
注意: 看這里的while條件
(kCFRunLoopRunStopped != result && kCFRunLoopRunFinished != result)
// CFRunLoopRun
void CFRunLoopRun(void) { /* DOES CALLOUT */
int32_t result;
do {
result = CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
CHECK_FOR_FORK();
} while (kCFRunLoopRunStopped != result && kCFRunLoopRunFinished != result);
}
// CFRunLoopRunSpecific
NSInt32 CFRunLoopRunSpecific(CFRunLoopRef rl, CFStringRef modeName, CFTimeInterval seconds, Boolean returnAfterSourceHandled) { /* DOES CALLOUT */
CHECK_FOR_FORK();
if (__CFRunLoopIsDeallocating(rl)) return kCFRunLoopRunFinished;
__CFRunLoopLock(rl);
CFRunLoopModeRef currentMode = __CFRunLoopFindMode(rl, modeName, false);
if (NULL == currentMode || __CFRunLoopModeIsEmpty(rl, currentMode, rl->_currentMode)) {
Boolean did = false;
if (currentMode) __CFRunLoopModeUnlock(currentMode);
__CFRunLoopUnlock(rl);
return did ? kCFRunLoopRunHandledSource : kCFRunLoopRunFinished;
}
volatile _per_run_data *previousPerRun = __CFRunLoopPushPerRunData(rl);
CFRunLoopModeRef previousMode = rl->_currentMode;
rl->_currentMode = currentMode;
int32_t result = kCFRunLoopRunFinished;
// 通知 observers 狀態(tài)發(fā)生變化意述,進(jìn)入loop
if (currentMode->_observerMask & kCFRunLoopEntry ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopEntry);
// RunLoop里面具體要做的事情, 主要是一個(gè)循環(huán)
result = __CFRunLoopRun(rl, currentMode, seconds, returnAfterSourceHandled, previousMode);
// 通知 observers 狀態(tài)發(fā)生變化吮蛹,退出loop
if (currentMode->_observerMask & kCFRunLoopExit ) __CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
__CFRunLoopModeUnlock(currentMode);
__CFRunLoopPopPerRunData(rl, previousPerRun);
rl->_currentMode = previousMode;
__CFRunLoopUnlock(rl);
return result;
}
第二步:開(kāi)啟一個(gè) do while 來(lái)被绯纾活線程,通知 Observers匹涮,RunLoop狀態(tài)變化: kCFRunLoopBeforeTimers
天试, 處理 Timer 回調(diào)
第三步:通知 Observers,RunLoop狀態(tài)變化: kCFRunLoopBeforeSources
然低,處理 Source0 回調(diào)
第四步:然后執(zhí)行加入RunLoop的 block回調(diào)喜每,接著會(huì)觸發(fā) Source0 回調(diào),接著可能會(huì)再次執(zhí)行加入的 block回調(diào)雳攘,如果有 Source1 是 ready
狀態(tài)的話带兜,就會(huì)跳轉(zhuǎn)到 handle_msg 去處理消息代碼如下:
第五步:通知 Observers,RunLoop狀態(tài)變化:kCFRunLoopBeforeWaiting
吨灭,線程將進(jìn)入休眠(sleep)狀態(tài)
第六步:進(jìn)入休眠后刚照,會(huì)等待 mach_port 的消息再次喚醒
第七步:通知 Observer,RunLoop狀態(tài)變化:kCFRunLoopAfterWaiting
喧兄,接收到 mach_port 消息无畔,RunLoop 的線程被喚醒了
第八步:RunLoop 被喚醒后開(kāi)始處理消息了:
- 如果是 Timer 時(shí)間到了,觸發(fā) Timer 的回調(diào)
- 如果是 dispatch 吠冤,執(zhí)行 block回調(diào)
- 如果是 source1 事件浑彰,處理這個(gè)事件回調(diào)
第九步:執(zhí)行加入的 block回調(diào)
第十步:根據(jù)RunLoop的狀態(tài)來(lái)判斷是否需要走下一個(gè) loop,結(jié)束循環(huán) 或者 回到外層循環(huán)進(jìn)入第二步
// __CFRunLoopRun
static int32_t __CFRunLoopRun(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFTimeInterval seconds, Boolean stopAfterHandle, CFRunLoopModeRef previousMode) {
uint64_t startTSR = mach_absolute_time();
int32_t retVal = 0;
do {
...
// 通知 Observers RunLoop 狀態(tài)發(fā)生變化 觸發(fā) Timer 回調(diào)
if (rlm->_observerMask & kCFRunLoopBeforeTimers) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeTimers);
// 通知 Observers RunLoop 狀態(tài)發(fā)生變化 觸發(fā) Source0 回調(diào)
if (rlm->_observerMask & kCFRunLoopBeforeSources) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeSources);
// 接著執(zhí)行加入的 block回調(diào)
__CFRunLoopDoBlocks(rl, rlm);
// 接著觸發(fā) Source0 回調(diào)
Boolean sourceHandledThisLoop = __CFRunLoopDoSources0(rl, rlm, stopAfterHandle);
// 可能會(huì)再次執(zhí)行加入的 block回調(diào)
if (sourceHandledThisLoop) {
__CFRunLoopDoBlocks(rl, rlm);
}
// 接著如果有 Source1 是 ready 狀態(tài)的話拯辙,就會(huì)跳轉(zhuǎn)到 handle_msg 去處理消息
if (MACH_PORT_NULL != dispatchPort && !didDispatchPortLastTime) {
msg = (mach_msg_header_t *)msg_buffer;
if (__CFRunLoopServiceMachPort(dispatchPort, &msg, sizeof(msg_buffer), &livePort, 0, &voucherState, NULL)) {
goto handle_msg;
}
}
...
//
if (!poll && (rlm->_observerMask & kCFRunLoopBeforeWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeWaiting);
...
// 等待喚醒
do {
__CFRunLoopServiceMachPort(waitSet, &msg, sizeof(msg_buffer), &livePort, poll ? 0 : TIMEOUT_INFINITY, &voucherState, &voucherCopy);
// 基于port的source事件郭变,調(diào)用者喚醒
if (modeQueuePort != MACH_PORT_NULL && livePort == modeQueuePort) {
while (_dispatch_runloop_root_queue_perform_4CF(rlm->_queue));
// Timer 時(shí)間到颜价、RunLoop 超時(shí)
if (rlm->_timerFired) {
rlm->_timerFired = false;
break;
} else {
if (msg && msg != (mach_msg_header_t *)msg_buffer) free(msg);
}
} else {
break;
}
} while (1);
...
// 接收到 mach_port 消息, RunLoop 的線程被喚醒了
if (!poll && (rlm->_observerMask & kCFRunLoopAfterWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopAfterWaiting);
handle_msg:;
...
// 接著開(kāi)始處理消息
// 如果 Timer 時(shí)間到诉濒,就觸發(fā) Timer 回調(diào)
if (msg-is-timer) {
if (!__CFRunLoopDoTimers(rl, rlm, mach_absolute_time())) {
// Re-arm the next timer, because we apparently fired early
__CFArmNextTimerInMode(rlm, rl);
}
}
// 如果 dispatch 就執(zhí)行 block
else if (msg_is_dispatch) {
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(msg);
}
// Source1 事件的話周伦,就處理這個(gè)事件
else {
CFRunLoopSourceRef source1 = __CFRunLoopModeFindSourceForMachPort(runloop, currentMode, livePort);
sourceHandledThisLoop = __CFRunLoopDoSource1(runloop, currentMode, source1, msg);
if (sourceHandledThisLoop) {
mach_msg(reply, MACH_SEND_MSG, reply);
}
}
...
// 執(zhí)行加入的 block回調(diào)
__CFRunLoopDoBlocks(rl, rlm);
// loop 已經(jīng)走完,這里要根據(jù)RunLoop 的狀態(tài)來(lái)判斷是否需要走下一個(gè) loop未荒,
if (sourceHandledThisLoop && stopAfterHandle) {
// 事件已處理完
retVal = kCFRunLoopRunHandledSource;
} else if (timeout_context->termTSR < mach_absolute_time()) {
// 設(shè)置了超時(shí)時(shí)間专挪,超時(shí)返回
retVal = kCFRunLoopRunTimedOut;
} else if (__CFRunLoopIsStopped(rl)) {
// 外部調(diào)用者強(qiáng)制停止
__CFRunLoopUnsetStopped(rl);
retVal = kCFRunLoopRunStopped;
} else if (rlm->_stopped) {
// 停止?fàn)顟B(tài)
rlm->_stopped = false;
retVal = kCFRunLoopRunStopped;
} else if (__CFRunLoopModeIsEmpty(rl, rlm, previousMode)) {
// mode 為空,RunLoop 結(jié)束
retVal = kCFRunLoopRunFinished;
}
} while (0 == retVal);
return retVal;
}