IOS 多线程 RUNLOOP 机制 (二)

来源:互联网 发布:php磁力解析源码 编辑:程序博客网 时间:2024/04/25 20:19
二,何时使用Run Loop
对于辅助线程,在需要和线程有更多交互时,才使用Run Loop。
比如:1)使用端口或者自定义输入源来和其他线程通讯
2)使用线程定时器
3)Cocoa中使用任何performSelector...的方法(参考Table:Performing selectors on other threads
4)使线程周期性工作

三,如何使用Run Loop对象
Run Loop对象提供了添加输入源,定时器和Run Loop的观察者以及启动Run Loop的接口,使用Run Loop包活获取--配置--启动--退出四个过程
1,获取Run Loop的对象
A,通过NSRunLoop获取
// 获得当前thread的Run loop
NSRunLoop *myRunLoop = [NSRunLoop currentRunLoop];
// 将Cocoa的NSRunLoop类型转换程Core Foundation的CFRunLoopRef类型
CFRunLoopRef ç = [myRunLoop getCFRunLoop];
B,使用CFRunLoopGetCurrent()函数
2,配置Run Loop
所谓配置Run Loop主要是给Run Loop添加输入源,定时器或者添加观察者,即设置Run Loop模式。上面函数- (void)observerRunLoop就是配置了一个带有观察者,添加了一个定时器的Run Loop线程。相关对象---CFRunLoopObserverRef对象和CFRunLoopAddObserver函数
3,启动Run Loop
一个Run Loop通常必须包含一个输入源或者定时器来监听事件,如果一个都没有,Run Loop启动后立即退出。
启动Run Loop的方式
1)无条件的---最简单的启动方法,但是退出Run Loop的唯一方式就是杀死它。
2)设置超时时间---预设超时时间来运行Run Loop。Run Loop运行直到某一事件到达或者规定的时间已经到期。
A,如果是事件到达,消息被传递给相应的处理程序来处理,然后Run Loop退出。可以循环重启Run Loop来等待下一事件。
B,如果是规定的时间到期了,可以使用此段时间来做任何的其他工作,然后Run Loop退出,或者直接循环重启Run Loop。
3)特定模式
使用特定模式运行Run Loop
=====Running a run loop: skeleton
- (void)skeletonThreadMain
{
BOOL done = NO;
// Set up a autorelease pool here if not using garbage collection.
.........
// Add Sources/Timers to the run loop  and do any other setup
.........

// The cycle of run loop
do
{
// start  the run loop but return after each source is handled
SInt32 result = CFRunLoopRunInMode( kCFRunLoopDefault, 10, YES );

// if a source explicitly stopped the run loop, or if there are no sources or timers, go ahead and exit.
if( (result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished) )
done = YES;

// Check for any other exit conditions here and set the "done" variable as needed
.........
}while(!done)

// Clean up code here. Be sure to release any allocated autorelease pools
.........
}
注:可以递归运行Run Loop,即可以使用CFRunLoopRun,CFRunLoopRunInMode或者任一NSRunLoop的方法在输入源或者定时器的处理程序里面启动Run Loop
4,退出Run Loop
有两种方法可以让Run Loop在处理事件之前退出
A,给Run Loop设置超时时间
B,通知Run Loop停止---使用CFRunLoopStopped函数可以显式停止run loop
5,线程安全和Run Loop对象
NSRunLoop线程不安全
CFRunLoop线程安全
对Run Loop对象的修改尽可能在所有线程内部完成这些操作