runloop相关内容最近拿出来复习一下。
前排首先墙裂推荐一篇收藏已久的文章:
https://blog.ibireme.com/2015/05/18/runloop/
可以先看后半部分的示例代码。代码都贴在文中都很简单。再回头结合起来看。上述文章讲的比较细致,推荐阅读。
一、runloop是什么的
一般当我们创建一个线程去执行任务,任务执行完毕线程就会退出。想要线程一直运行,需要一个循环来维持。
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread_in) object:nil];
[thread start];
- (void)thread_in {
do{
do_something();
}while (something_happen);
}
runloop就是做了这样一件事情,保持线程不退出循环执行任务。
二、runloop内有什么
首先线程和runloop对象是一一对应的,即一个线程对应一个runloop对象。但是runloop本身并不是一个简单的循环。runloop循环内执行的事件会按照不同的mode进行分组(就类似应用服务器上用户分组一样)。
CFRunLoopMode在runloop中:
struct __CFRunLoopMode {
CFStringRef _name; // Mode Name, 例如 @"kCFRunLoopDefaultMode"
CFMutableSetRef _sources0; // Set
CFMutableSetRef _sources1; // Set
CFMutableArrayRef _observers; // Array
CFMutableArrayRef _timers; // Array
...
};
struct __CFRunLoop {
CFMutableSetRef _commonModes; // Set
CFMutableSetRef _commonModeItems; // Set
CFRunLoopModeRef _currentMode; // Current Runloop Mode
CFMutableSetRef _modes; // Set
...
};
可以看出CFRunLoop结构体中包含的是mode的集合,mode中包含的是事件,计时器,观察者的集合。
_commonModes:标记为‘Common’的mode的集合
_commonModeItems:这是一个 Source/Observer/Timer 的集合。该集合内的事件会被在有common标记的mode内执行
主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。DefaultMode 是 App 平时所处的状态,TrackingRunLoopMode 是追踪 ScrollView 滑动时的状态。
CFRunLoopSourceRef
是事件产生的地方。Source有两个版本:Source0 和 Source1。
• Source0 只包含了一个回调(函数指针),它并不能主动触发事件。
• Source1 包含了一个 mach_port 和一个回调(函数指针),被用于通过内核和其他线程相互发送消息。
CFRunLoopTimerRef
是基于时间的触发器,当其加入到 RunLoop 时,RunLoop会注册对应的时间点,当时间点到时,RunLoop会被唤醒以执行那个回调。
CFRunLoopObserverRef
是观察者,每个 Observer 都包含了一个回调(函数指针),当 RunLoop 的状态发生变化时,观察者就能通过回调接受到这个变化。
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0), // 即将进入Loop
kCFRunLoopBeforeTimers = (1UL << 1), // 即将处理 Timer
kCFRunLoopBeforeSources = (1UL << 2), // 即将处理 Source
kCFRunLoopBeforeWaiting = (1UL << 5), // 即将进入休眠
kCFRunLoopAfterWaiting = (1UL << 6), // 刚从休眠中唤醒
kCFRunLoopExit = (1UL << 7), // 即将退出Loop
};
这几个时间节点可以注册观察
三、runloop内怎么运行
/// 用DefaultMode启动
void CFRunLoopRun(void) {
CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
}
/// 用指定的Mode启动,允许设置RunLoop超时时间
int CFRunLoopRunInMode(CFStringRef modeName, CFTimeInterval seconds, Boolean stopAfterHandle) {
return CFRunLoopRunSpecific(CFRunLoopGetCurrent(), modeName, seconds, returnAfterSourceHandled);
}
/// RunLoop的实现
int CFRunLoopRunSpecific(runloop, modeName, seconds, stopAfterHandle) {
/// 首先根据modeName找到对应mode
CFRunLoopModeRef currentMode = __CFRunLoopFindMode(runloop, modeName, false);
/// 如果mode里没有source/timer/observer, 直接返回。
if (__CFRunLoopModeIsEmpty(currentMode)) return;
/// 1. 通知 Observers: RunLoop 即将进入 loop。
__CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopEntry);
/// 内部函数,进入loop
__CFRunLoopRun(runloop, currentMode, seconds, returnAfterSourceHandled) {
Boolean sourceHandledThisLoop = NO;
int retVal = 0;
do {
/// 2. 通知 Observers: RunLoop 即将触发 Timer 回调。
__CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeTimers);
/// 3. 通知 Observers: RunLoop 即将触发 Source0 (非port) 回调。
__CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeSources);
/// 执行被加入的block
__CFRunLoopDoBlocks(runloop, currentMode);
/// 4. RunLoop 触发 Source0 (非port) 回调。
sourceHandledThisLoop = __CFRunLoopDoSources0(runloop, currentMode, stopAfterHandle);
/// 执行被加入的block
__CFRunLoopDoBlocks(runloop, currentMode);
/// 5. 如果有 Source1 (基于port) 处于 ready 状态,直接处理这个 Source1 然后跳转去处理消息。
if (__Source0DidDispatchPortLastTime) {
Boolean hasMsg = __CFRunLoopServiceMachPort(dispatchPort, &msg)
if (hasMsg) goto handle_msg;
}
/// 通知 Observers: RunLoop 的线程即将进入休眠(sleep)。
if (!sourceHandledThisLoop) {
__CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopBeforeWaiting);
}
/// 7. 调用 mach_msg 等待接受 mach_port 的消息。线程将进入休眠, 直到被下面某一个事件唤醒。
/// • 一个基于 port 的Source 的事件。
/// • 一个 Timer 到时间了
/// • RunLoop 自身的超时时间到了
/// • 被其他什么调用者手动唤醒
__CFRunLoopServiceMachPort(waitSet, &msg, sizeof(msg_buffer), &livePort) {
mach_msg(msg, MACH_RCV_MSG, port); // thread wait for receive msg
}
/// 8. 通知 Observers: RunLoop 的线程刚刚被唤醒了。
__CFRunLoopDoObservers(runloop, currentMode, kCFRunLoopAfterWaiting);
/// 收到消息,处理消息。
handle_msg:
/// 9.1 如果一个 Timer 到时间了,触发这个Timer的回调。
if (msg_is_timer) {
__CFRunLoopDoTimers(runloop, currentMode, mach_absolute_time())
}
/// 9.2 如果有dispatch到main_queue的block,执行block。
else if (msg_is_dispatch) {
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(msg);
}
/// 9.3 如果一个 Source1 (基于port) 发出事件了,处理这个事件
else {
CFRunLoopSourceRef source1 = __CFRunLoopModeFindSourceForMachPort(runloop, currentMode, livePort);
sourceHandledThisLoop = __CFRunLoopDoSource1(runloop, currentMode, source1, msg);
if (sourceHandledThisLoop) {
mach_msg(reply, MACH_SEND_MSG, reply);
}
}
/// 执行加入到Loop的block
__CFRunLoopDoBlocks(runloop, currentMode);
if (sourceHandledThisLoop && stopAfterHandle) {
/// 进入loop时参数说处理完事件就返回。
retVal = kCFRunLoopRunHandledSource;
} else if (timeout) {
/// 超出传入参数标记的超时时间了
retVal = kCFRunLoopRunTimedOut;
} else if (__CFRunLoopIsStopped(runloop)) {
/// 被外部调用者强制停止了
retVal = kCFRunLoopRunStopped;
} else if (__CFRunLoopModeIsEmpty(runloop, currentMode)) {
/// source/timer/observer一个都没有了
retVal = kCFRunLoopRunFinished;
}
/// 如果没超时,mode里没空,loop也没被停止,那继续loop。
} while (retVal == 0);
}
/// 10. 通知 Observers: RunLoop 即将退出。
__CFRunLoopDoObservers(rl, currentMode, kCFRunLoopExit);
}
从上面代码可以看出runloop 可以根据不同的mode进入函数执行循环。循环内执行source,time,observe事件,直至退出循环。
循环内mach_msg是系统调度内核的消息传递方式。runloop运行于操作系统内核之上(内核的调度主要是完成多任务程序,保证系统实时性,这又是另一方世界,可以自行学习)。
四、简单动手
新建一个工程吧UI线程的runloop打印出来
NSLog(@"%@",[NSRunLoop mainRunLoop]);
看打印出来的内容
<CFRunLoop 0x600003980000 [0x7fff8062d610]>{wakeup port = 0x2307, stopped = false, ignoreWakeUps = false,
current mode = kCFRunLoopDefaultMode,
common modes = <CFBasicHash 0x600000ba3e10 [0x7fff8062d610]>{type = mutable set, count = 2,
entries =>
0 : <CFString 0x7fff8692c2c0 [0x7fff8062d610]>{contents = "UITrackingRunLoopMode"}
2 : <CFString 0x7fff806408e0 [0x7fff8062d610]>{contents = "kCFRunLoopDefaultMode"}
}
,
common mode items = <CFBasicHash 0x600000b8e6a0 [0x7fff8062d610]>{type = mutable set, count = 11,
entries =>
0 : <CFRunLoopSource 0x600003090240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x7fff38ba7a0e)}}
1 : <CFRunLoopSource 0x6000030800c0 [0x7fff8062d610]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x60000219d380, callout = FBSSerialQueueRunLoopSourceHandler (0x7fff36cf7bd5)}}
2 : <CFRunLoopObserver 0x6000034980a0 [0x7fff8062d610]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x7fff48810abe), context = <CFRunLoopObserver context 0x600002e98930>}
3 : <CFRunLoopObserver 0x600003498280 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (
0 : <0x7fbb2800f038>
)}}
4 : <CFRunLoopSource 0x600003094300 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x600000bde6a0, callout = __handleHIDEventFetcherDrain (0x7fff48d28f61)}}
5 : <CFRunLoopObserver 0x600003498320 [0x7fff8062d610]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (
0 : <0x7fbb2800f038>
)}}
6 : <CFRunLoopObserver 0x600003498140 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x7fff48cb5ad3), context = <CFRunLoopObserver context 0x7fbb289043f0>}
7 : <CFRunLoopObserver 0x6000034841e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x7fff2b454f32), context = <CFRunLoopObserver context 0x0>}
10 : <CFRunLoopObserver 0x6000034981e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x7fff48cb5b3c), context = <CFRunLoopObserver context 0x7fbb289043f0>}
11 : <CFRunLoopSource 0x600003088240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x4c03, callout = PurpleEventCallback (0x7fff38ba7a1a)}}
12 : <CFRunLoopSource 0x600003094180 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x600003e980d0, callout = __handleEventQueue (0x7fff48d28ef2)}}
}
,
modes = <CFBasicHash 0x600000ba3de0 [0x7fff8062d610]>{type = mutable set, count = 3,
entries =>
0 : <CFRunLoopMode 0x600003e80000 [0x7fff8062d610]>{name = UITrackingRunLoopMode, port set = 0x5303, queue = 0x600002b8c600, source = 0x600002b8c700 (not fired), timer port = 0x5203,
sources0 = <CFBasicHash 0x600000b8e700 [0x7fff8062d610]>{type = mutable set, count = 4,
entries =>
0 : <CFRunLoopSource 0x600003090240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x7fff38ba7a0e)}}
2 : <CFRunLoopSource 0x600003094180 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x600003e980d0, callout = __handleEventQueue (0x7fff48d28ef2)}}
5 : <CFRunLoopSource 0x6000030800c0 [0x7fff8062d610]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x60000219d380, callout = FBSSerialQueueRunLoopSourceHandler (0x7fff36cf7bd5)}}
6 : <CFRunLoopSource 0x600003094300 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x600000bde6a0, callout = __handleHIDEventFetcherDrain (0x7fff48d28f61)}}
}
,
sources1 = <CFBasicHash 0x600000b8e730 [0x7fff8062d610]>{type = mutable set, count = 1,
entries =>
1 : <CFRunLoopSource 0x600003088240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x4c03, callout = PurpleEventCallback (0x7fff38ba7a1a)}}
}
,
observers = (
"<CFRunLoopObserver 0x600003498320 [0x7fff8062d610]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7fbb2800f038>\n)}}",
"<CFRunLoopObserver 0x6000034980a0 [0x7fff8062d610]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x7fff48810abe), context = <CFRunLoopObserver context 0x600002e98930>}",
"<CFRunLoopObserver 0x600003498140 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x7fff48cb5ad3), context = <CFRunLoopObserver context 0x7fbb289043f0>}",
"<CFRunLoopObserver 0x6000034841e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x7fff2b454f32), context = <CFRunLoopObserver context 0x0>}",
"<CFRunLoopObserver 0x6000034981e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x7fff48cb5b3c), context = <CFRunLoopObserver context 0x7fbb289043f0>}",
"<CFRunLoopObserver 0x600003498280 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7fbb2800f038>\n)}}"
),
timers = (null),
currently 616574172 (108542777673233) / soft deadline in: 1.84466355e+10 sec (@ -1) / hard deadline in: 1.84466355e+10 sec (@ -1)
},
1 : <CFRunLoopMode 0x600003e800d0 [0x7fff8062d610]>{name = GSEventReceiveRunLoopMode, port set = 0x2d03, queue = 0x600002b8c780, source = 0x600002b8c880 (not fired), timer port = 0x5003,
sources0 = <CFBasicHash 0x600000b8e7c0 [0x7fff8062d610]>{type = mutable set, count = 1,
entries =>
0 : <CFRunLoopSource 0x600003090240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x7fff38ba7a0e)}}
}
,
sources1 = <CFBasicHash 0x600000b8e7f0 [0x7fff8062d610]>{type = mutable set, count = 1,
entries =>
1 : <CFRunLoopSource 0x600003088300 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x4c03, callout = PurpleEventCallback (0x7fff38ba7a1a)}}
}
,
observers = (null),
timers = (null),
currently 616574172 (108542780009825) / soft deadline in: 1.84466355e+10 sec (@ -1) / hard deadline in: 1.84466355e+10 sec (@ -1)
},
2 : <CFRunLoopMode 0x600003e94000 [0x7fff8062d610]>{name = kCFRunLoopDefaultMode, port set = 0x2003, queue = 0x600002b84800, source = 0x600002b80480 (not fired), timer port = 0x1e03,
sources0 = <CFBasicHash 0x600000b8e760 [0x7fff8062d610]>{type = mutable set, count = 4,
entries =>
0 : <CFRunLoopSource 0x600003090240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x0, callout = PurpleEventSignalCallback (0x7fff38ba7a0e)}}
2 : <CFRunLoopSource 0x600003094180 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 0, info = 0x600003e980d0, callout = __handleEventQueue (0x7fff48d28ef2)}}
5 : <CFRunLoopSource 0x6000030800c0 [0x7fff8062d610]>{signalled = No, valid = Yes, order = 0, context = <CFRunLoopSource context>{version = 0, info = 0x60000219d380, callout = FBSSerialQueueRunLoopSourceHandler (0x7fff36cf7bd5)}}
6 : <CFRunLoopSource 0x600003094300 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -2, context = <CFRunLoopSource context>{version = 0, info = 0x600000bde6a0, callout = __handleHIDEventFetcherDrain (0x7fff48d28f61)}}
}
,
sources1 = <CFBasicHash 0x600000b8e790 [0x7fff8062d610]>{type = mutable set, count = 1,
entries =>
1 : <CFRunLoopSource 0x600003088240 [0x7fff8062d610]>{signalled = No, valid = Yes, order = -1, context = <CFRunLoopSource context>{version = 1, info = 0x4c03, callout = PurpleEventCallback (0x7fff38ba7a1a)}}
}
,
observers = (
"<CFRunLoopObserver 0x600003498320 [0x7fff8062d610]>{valid = Yes, activities = 0x1, repeats = Yes, order = -2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7fbb2800f038>\n)}}",
"<CFRunLoopObserver 0x6000034980a0 [0x7fff8062d610]>{valid = Yes, activities = 0x20, repeats = Yes, order = 0, callout = _UIGestureRecognizerUpdateObserver (0x7fff48810abe), context = <CFRunLoopObserver context 0x600002e98930>}",
"<CFRunLoopObserver 0x600003498140 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 1999000, callout = _beforeCACommitHandler (0x7fff48cb5ad3), context = <CFRunLoopObserver context 0x7fbb289043f0>}",
"<CFRunLoopObserver 0x6000034841e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2000000, callout = _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv (0x7fff2b454f32), context = <CFRunLoopObserver context 0x0>}",
"<CFRunLoopObserver 0x6000034981e0 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2001000, callout = _afterCACommitHandler (0x7fff48cb5b3c), context = <CFRunLoopObserver context 0x7fbb289043f0>}",
"<CFRunLoopObserver 0x600003498280 [0x7fff8062d610]>{valid = Yes, activities = 0xa0, repeats = Yes, order = 2147483647, callout = _wrapRunLoopWithAutoreleasePoolHandler (0x7fff48c84b28), context = <CFArray 0x600000bfc2a0 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (\n\t0 : <0x7fbb2800f038>\n)}}"
),
timers = <CFArray 0x600002190540 [0x7fff8062d610]>{type = mutable-small, count = 1, values = (
0 : <CFRunLoopTimer 0x600003090300 [0x7fff8062d610]>{valid = Yes, firing = No, interval = 0, tolerance = 0, next fire date = 616574174 (1.45552099 @ 108544238485402), callout = (Delayed Perform) UIApplication _accessibilitySetUpQuickSpeak (0x7fff2593abc0 / 0x7fff481ab39b) (/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore), context = <CFRunLoopTimer context 0x60000108e580>}
)},
currently 616574172 (108542780315622) / soft deadline in: 1.45816976 sec (@ 108544238485402) / hard deadline in: 1.45816963 sec (@ 108544238485402)
},
}
}
可以看到runloop的当前mode是kCFRunLoopDefaultMode。主线程runloop内总共有三个model。UITrackingRunLoopMode、kCFRunLoopDefaultMode、GSEventReceiveRunLoopMode。
被标记为common mode的有UITrackingRunLoopMode和kCFRunLoopDefaultMode。
DefaultMode 是线程平时所处的状态,TrackingRunLoopMode 是追踪 ScrollView 滑动时的状态。另一个mode我也不知道是做什么的,可以自行查阅。
现在我们在主线程创建一个NSTimer 再次打印主线程runloop信息:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer_log) userInfo:nil repeats:YES];
NSLog(@"%@",[NSRunLoop mainRunLoop]);
打印信息太占篇幅就不群贴出来了,总体和上面差不多,我们看差异部分:
对比上一条日志可以看出在主线程的runloop 的kCFRunLoopDefaultMode 中多了一个CFRunloopTimer对象。
现在我们在创建一个UIScrollView
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer_log) userInfo:nil repeats:YES];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scroll.contentSize = CGSizeMake(0, self.view.bounds.size.height * 2);
[self.view addSubview:scroll];
}
- (void)timer_log {
NSLog(@"timer_log");
}
程序跑起来正常打印日志timer_log,但是当滑动scrollview的时候日志暂停输出。
中间这段时间我在滑动scrollview,日志便中断了。
前文中说过kCFRunLoopDefaultMode是线程正常运行的mode,UITrackingRunLoopMode是界面跟踪 Mode,用于 ScrollView 追踪触摸滑动,保证界面滑动时不受其他 Mode 影响。所以当我们滑动scrollview的时候主线程的runloop切换到UITrackingRunLoopMode的循环, kCFRunLoopDefaultMode内的timer自然就无响应。
这时候我们将上述创建的timer加入到UITrackingRunLoopMode,这样的话我们在滑动scrollview的时候timer也可以正常运行。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer_log) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scroll.contentSize = CGSizeMake(0, self.view.bounds.size.height * 2);
[self.view addSubview:scroll];
}
- (void)timer_log {
NSLog(@"timer_log");
}
在循环内代码是顺序执行的,如果将过多的内容添加到UITrackingRunLoopMode。有可能会造成界面卡顿。当然界面卡顿绝不仅仅是这个原因。哪怕其他mode下 线程堵塞住了,界面也会有卡顿。毕竟都是在一个线程里面的。
五、监控界面卡顿
上文中runloop循环内发生状态切换的时候会执行__CFRunLoopDoObservers函数将当前状态信息反馈给Observers。总的来说,线程卡顿主要原因还是执行任务,我们监听执行任务前的状态,若果在规定时间内未发生变化,即认为线程卡住了。kCFRunLoopBeforeSources,kCFRunLoopAfterWaiting,这里监听这两个状态。
#import "ViewController.h"
@interface ViewController ()
{
CFRunLoopObserverRef observer;
dispatch_semaphore_t semaphore;
CFRunLoopActivity currentActivity;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer_log) userInfo:nil repeats:YES];
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scroll.contentSize = CGSizeMake(0, self.view.bounds.size.height * 2);
[self.view addSubview:scroll];
CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL};
//注册observer 监听kCFAllocatorDefault mode下的所有状态回调
observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
kCFRunLoopAllActivities,
YES,
0,
&runLoopObserverCallBack,
&context);
//将观察者添加到主线程runloop的common模式下的观察中
CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
//创建信号量
semaphore = dispatch_semaphore_create(0); //Dispatch Semaphore保证同步
//创建子线程监控
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//循环利用信号量等待进行判断
while (YES) {
//获取信号量等待1s
long semaphoreWait = dispatch_semaphore_wait(self->semaphore, dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC));
//如果1S没有获得信号量,且未获得信号量的状态为kCFRunLoopBeforeSources 或者kCFRunLoopAfterWaiting 即可判定为卡顿
if (semaphoreWait != 0) {
if (!self->observer) {
self->semaphore = 0;
self->currentActivity = 0;
return;
}
//选择监控状态
if (self->currentActivity == kCFRunLoopBeforeSources || self->currentActivity == kCFRunLoopAfterWaiting) {
NSLog(@"卡了");
}
}
}
});
}
- (void)timer_log {
//这里循环睡眠2s 造成线程卡顿
sleep(2);
}
static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
//在监控回调中释放信号量并记录当前runloop状态
ViewController *m = (__bridge ViewController*)info;
m->currentActivity = activity;
dispatch_semaphore_t semaphore = m->semaphore;
dispatch_semaphore_signal(semaphore);
}
这段代码运用timer循环睡眠线程造成卡顿,每次睡眠2s,而我们监测时长设置为1s。程序运行起来即可看到日志行输出卡顿。
因为上述代码利用的timer睡眠线程来造成卡顿,所以只要监听kCFRunLoopAfterWaiting状态变化迟缓即可获得线程卡顿的结果。而监控kCFRunLoopBeforeSources是监控不到上述代码卡顿结果的。(代码比较简单,大家可以尝试一下)
六、线程卡顿的集中情况
1.复杂 UI 、图文混排的绘制量过大
2.在主线程上做网络同步请求
3.在主线程做大量的 IO 操作
4.运算量过大,CPU 持续高占用
5.死锁和主子线程抢锁
以上场景总结也是参考他文,我并没有全部遇到。
可以留言交流。