Skip to content

Instantly share code, notes, and snippets.

@zhangkn
Last active May 4, 2018 08:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkn/17ee74e1af575bc7253562a064b6e64a to your computer and use it in GitHub Desktop.
Save zhangkn/17ee74e1af575bc7253562a064b6e64a to your computer and use it in GitHub Desktop.
CFRunLoopGetCurrent
/// 全局的Dictionary,key 是 pthread_t, value 是 CFRunLoopRef
static CFMutableDictionaryRef loopsDic;//线程和 RunLoop 之间是一一对应的,其关系是保存在一个全局的 Dictionary 里
/// 访问 loopsDic 时的锁
static CFSpinLock_t loopsLock;
/// 获取一个 pthread 对应的 RunLoop。
CFRunLoopRef _CFRunLoopGet(pthread_t thread) {
OSSpinLockLock(&loopsLock);
if (!loopsDic) {//线程刚创建时并没有 RunLoop,如果你不主动获取,那它一直都不会有
// 第一次进入时,初始化全局Dic,并先为主线程创建一个 RunLoop。
loopsDic = CFDictionaryCreateMutable();
CFRunLoopRef mainLoop = _CFRunLoopCreate();//RunLoop 的创建是发生在第一次获取时
CFDictionarySetValue(loopsDic, pthread_main_thread_np(), mainLoop);
}
/// 直接从 Dictionary 里获取。
CFRunLoopRef loop = CFDictionaryGetValue(loopsDic, thread));
if (!loop) {
/// 取不到时,创建一个
loop = _CFRunLoopCreate();
CFDictionarySetValue(loopsDic, thread, loop);
/// 注册一个回调,当线程销毁时,顺便也销毁其对应的 RunLoop。
_CFSetTSD(..., thread, loop, __CFFinalizeRunLoop);//RunLoop 的销毁是发生在线程结束时
}
OSSpinLockUnLock(&loopsLock);
return loop;
}
CFRunLoopRef CFRunLoopGetMain() {
return _CFRunLoopGet(pthread_main_thread_np());//获取主主线程;[NSThread mainThread]
}
CFRunLoopRef CFRunLoopGetCurrent() {//你只能在一个线程的内部获取其 RunLoop(主线程除外)
return _CFRunLoopGet(pthread_self());// [NSThread currentThread] 来获取当前线程
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment