1、多线程--单个应用程序内的多个代码执行路径
线程支持:run loop 、同步工具、线程间通信以及线程包。
线程包:{ NSThread :
[NSThread detachNewThreadSelector:@selector(testForOne:) toTarget:self withObject:@"qire"]; 立即创建一个线程
NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(testForTwo:) object:@"我是一个大企鹅"];
[myThread start]; 并不会立即创建一个线程,需要手动启动
以上两个当线程退出时,资源由系统自动回收,之后不需要在其他线程中显式链接--????
[self performSelectorOnMainThread:@selector(sendMessageToThread:) withObject:@"我给你发送了一条消息" waitUntilDone:YES]; 在当前的线程中执行任务,不新建
waitUntilDone:当前线程跟目标线程一致,设置yes:在当前线程立即执行消息
no:则在当前线程的run loop中排队等待执行。
[self performSelectorInBackground:@selector(sendMessageToThread:) withObject:@"我在后台运行了吗?”]; 会在后台, 新建一个线程
[self performSelector:@selector(sendMessageToThread:) withObject:@"我延时了5秒" afterDelay:5.0f]; 该方法的执行过程,等延时时间条件满足时,当前线程才尝试将该消息加入run loop 排队,准备执行 }
2、一个线程需要管理代码的数据结构组合--内核级与应用数据级
3、线程的并发---每个新的执行路径独立于main,一个个独立的线程
4、线程状态:running\ready\blocked
5、创建新的线程--指定入口函数(the code you want to do)
6、run loop 为线程监测 事件源,事件到达--调度事件到run loop--分配给指定程序
7、配置run loop:启动线程-获取run loop引用对象-设置事件处理程序-运行run loop
8、同步工具:原子操作、内存屏障、volatile变量、锁、条件、selector例程
9、线程通信:
Distributed objects is much more suitable for communicating with other processes, where the overhead of going between processes is already high.
Message queues:simple and convenient, they are not as efficient as some other communications techniques
direct message: automatically serialized on that thread.
condition: gate keeper
run loop: 事件驱动
port and socket: a more elaborate way to communication between two threads, but it is also a very reliable technique. More importantly, ports and sockets can be used to communicate with external entities, such as other processes and services. For efficiency, ports are implemented using run loop sources, so your thread sleeps when there is no data waiting on the port.
线程间通信、共享数据结构、线程退出时的行为、处理异常、中断线程
一个线程中默认都包含有一个run loop
网友评论