上回书说到源(sources), 源主要分2大类,
1 系统内核事件源
2 普通事件源
1 关于Input Source
以下是apple对输入源的官方解释
Input Sources
Input sources deliver events asynchronously to your threads. The source of the event depends on the type of the input source, which is generally one of two categories. Port-based input sources monitor your application’s Mach ports. Custom input sources monitor custom sources of events. As far as your run loop is concerned, it should not matter whether an input source is port-based or custom. The system typically implements input sources of both types that you can use as is. The only difference between the two sources is how they are signaled. Port-based sources are signaled automatically by the kernel, and custom sources must be signaled manually from another thread.
When you create an input source, you assign it to one or more modes of your run loop. Modes affect which input sources are monitored at any given moment. Most of the time, you run the run loop in the default mode, but you can specify custom modes too. If an input source is not in the currently monitored mode, any events it generates are held until the run loop runs in the correct mode.
输入源异步的向我们的线程传递事件, 事件源依赖输入源的类型, 输入源主要分2大类, 一种是基于port的(source1), 一种是普通输入源(source0), 只要你的runloop关心, 不应该考虑到底是哪种输入源, 系统通常会实现两种事件源. 两种源的唯一区别是信号的发出的方式, 一种是内核发出的, 一种是用户手动从其它线程发出的. 当你定义一种输入源,
你要为它指定runloop的模式, 这样就把这种模式下的响应监控起来了, 这将会影响事件的响应, 如果runloop当前没有运行在事件源监控的模式, 那么这时候产生的事件将会保存起来, 到runloop切回到事件源监控的模式, 才触发响应.
这就是为什么当我们不停的滑动首页, 导致广告不能自动滚动, 当我们松手时, 广告就连续滚动了2次, 因为当我们滑动首页的时候, runloop处于NSEventTrackingRunLoopMode
, 这时候timer这个事件源产生的事件被保存起来, 当runloop重新切回NSDefaultRunLoopMode
, 这时候timer产生的事件才被处理. 也就是因为因为runloop mode的变化导致, timer的触发节奏被打乱了, 但是如果你一直滑动, 导致timer的触发错过了多次, 也只会在切回来的时候触发一次, 然后再继续重新按照计划触发.
在AFN2.x, 我们会发现类似的代码
NSPort *macPort = [NSPort port];
NSRunLoop *subRunLoop = [NSRunLoop currentRunLoop];
[subRunLoop addPort:macPort forMode:NSDefaultRunLoopMode];
这是一种线程保活的方式, 我们通过给子线程的runloop添加source来让线程保活.
像performSelector
系列方法, 都是属于source0的, 这里不展开讲performSelector
, 后续将会专题讲.
2 Runloop Observer
下面看下source是什么时候被处理的.
一次runloop有以下几种状态, 我们可以通过监听CFRunLoopObserverRef
的CFRunLoopActivity
来知道当前runloop的状态,
kCFRunLoopEntry = (1UL << 0), // 进入runloop
kCFRunLoopBeforeTimers = (1UL << 1), // 即将处理timer
kCFRunLoopBeforeSources = (1UL << 2),// 即将处理source
kCFRunLoopBeforeWaiting = (1UL << 5), // 即将进入休眠
kCFRunLoopAfterWaiting = (1UL << 6), // 从休眠状态被唤醒, 但是还没开始处理事件
kCFRunLoopExit = (1UL << 7), // 退出runloop
从这里我们可以看到, timer source和source地位是相同的, 都是一次runloop要处理的事件, 但是我们通常说的source应该特指input source. 而通常说的timer应该指的是timer source.
3 一次Runloop做哪些事情
- 1.通知Observer, 已经进入runloop
- 2.通知Observer, 即将处理Timer
- 3.通知Observer, 即将处理Source0
- 4.处理Source0
- 5.如果有Source1, 立即处理, 跳到9.
- 6.通知Observer, 线程即将休眠(kCFRunLoopBeforeWaiting)
- 7.进入休眠, 直到有如下事件发生.
- a. source1(port).
- b. Timer.
- c. Runloop设置的超时时间到了.
- d. Runloop被唤醒.
- 8.通知Observer, 线程刚被唤醒(kCFRunLoopAfterWaiting)
- 9.处理唤醒时收到的消息
- a. 如果有Timer触发, 处理这个timer, 重新开启runloop, 跳到2.
- b. 如果有Source(Source0或者Source1), 传递这个事件.
- c. 如果还没有到超时时间, 重新开始runloop, 跳到2.
- 10.通知Observer, 即将退出Runloop(kCFRunLoopExit).
这里第七步有个明显的错误, 就是source0实际并不会立即唤醒runloop.这里应该是作者笔误了.
4 什么时候使用RunLoop
当我们需要在子线程中做以下事情的时候需要开启RunLoop
- 1 使用source0或者source1和其它线程交互.
- 2 使用timer.
- 3 使用
performSelector
系列方法. - 4 执行周期性任务.
当开启一个RunLoop前, 你必须至少添加一个source或者timer到当前RunLoop, 如果一个都没有, 那RunLoop一执行就结束了, 根本不会走到kCFRunLoopEntry
!
5 如何结束RunLoop
- 1 当RunLoop超时后, 自动结束
- 2 当RunLoop里的source和timer都处理完了, 会结束.
- 3 使用
CFRunLoopStop(CFRunLoopGetCurrent());
- (void)demo1 {
// 开启后台线程计时
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSRunLoop *curLoop = [NSRunLoop currentRunLoop];
_bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(onBgTimeout:) userInfo:nil repeats:YES];
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
switch (activity) {
case kCFRunLoopEntry:
NSLog(@"###子线程###进入kCFRunLoopEntry");
break;
case kCFRunLoopBeforeTimers:
NSLog(@"###子线程###即将处理Timer事件");
break;
case kCFRunLoopBeforeSources:
NSLog(@"###子线程###即将处理Source事件");
break;
case kCFRunLoopBeforeWaiting:
NSLog(@"###子线程###即将休眠");
break;
case kCFRunLoopAfterWaiting:
NSLog(@"###子线程###被唤醒");
break;
case kCFRunLoopExit:
NSLog(@"###子线程###退出RunLoop");
break;
default:
break;
}
});
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
[curLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
});
}
- (void)onBgTimeout:(NSTimer *)timer {
static int x = 1;
NSLog(@"thread:%@, curX:%@", [NSThread currentThread], @(x));
x++;
}
当RunLoop超时时间到, RunLoop退出.
- (void)demo2 {
// 当RunLoop里的source和timer都处理完了, 会结束.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
_bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(onBgTimeout:) userInfo:nil repeats:YES];
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
switch (activity) {
case kCFRunLoopEntry:
NSLog(@"###子线程###进入kCFRunLoopEntry");
break;
case kCFRunLoopBeforeTimers:
NSLog(@"###子线程###即将处理Timer事件");
break;
case kCFRunLoopBeforeSources:
NSLog(@"###子线程###即将处理Source事件");
break;
case kCFRunLoopBeforeWaiting:
NSLog(@"###子线程###即将休眠");
break;
case kCFRunLoopAfterWaiting:
NSLog(@"###子线程###被唤醒");
break;
case kCFRunLoopExit:
NSLog(@"###子线程###退出RunLoop");
break;
default:
break;
}
});
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
CFRunLoopRun();
});
}
- (void)onBgTimeout:(NSTimer *)timer {
static int x = 2;
NSLog(@"thread:%@, curX:%@", [NSThread currentThread], @(x));
x++;
if (x == 5) {
[_bgTimer invalidate];
_bgTimer = nil;
}
}
当_bgTimer
执行完, RunLoop退出.
- (void)demo3 {
// CFRunLoopStop
dispatch_async(dispatch_get_global_queue(0, 0), ^{
_bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(onBgTimeout:) userInfo:nil repeats:YES];
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
switch (activity) {
case kCFRunLoopEntry:
NSLog(@"###子线程###进入kCFRunLoopEntry");
break;
case kCFRunLoopBeforeTimers:
NSLog(@"###子线程###即将处理Timer事件");
break;
case kCFRunLoopBeforeSources:
NSLog(@"###子线程###即将处理Source事件");
break;
case kCFRunLoopBeforeWaiting:
NSLog(@"###子线程###即将休眠");
break;
case kCFRunLoopAfterWaiting:
NSLog(@"###子线程###被唤醒");
break;
case kCFRunLoopExit:
NSLog(@"###子线程###退出RunLoop");
break;
default:
break;
}
});
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
CFRunLoopRun();
});
}
- (void)onBgTimeout:(NSTimer *)timer {
static int x = 1;
NSLog(@"thread:%@, curX:%@", [NSThread currentThread], @(x));
x++;
if (x == 5) {
CFRunLoopStop(CFRunLoopGetCurrent());
}
}
当程序执行5次后, 虽然_bgTimer
没执行完, 但是强制stop了.