多线程的理解

来源:互联网 发布:天音软件 编辑:程序博客网 时间:2024/05/22 16:05

自己创建线程的一个问题是会为代码带来不确定性。线程是一种比较底层且复杂的对并发任务支持的一种方式。

如果没有充分理解,很可能会造成很多问题。另外一个要考虑的是,你是否真的需要线程,在没有必要的情况下尽量不要使用。

这个表里列出了线程的很多替代方案,也是更高级个上层的技术。


比较常用的创建线程的三种方式:

1、NSThread

2、POSIX threads(POSIX是linux上的线程函数,iOS来源与UNIX,所以也支持这些函数)

3、Multiprocessing Services(这种方式只有OS X上特有,iOS上没有此技术)

Runloop:

runloop用于管理线程中的异步事件,用来监听一个或多个事件源,一旦事件到来,系统会唤醒线程,并把这些事件分派

给线程,线程负责把相应处理这些事件,也就是调用他们的处理函数。它最大的好处就是可以创建一个常驻线程,有事干的时候唤醒,没事干的时候睡眠。

配置runloop很简单,每个线程都有自己相关的runloop,而主线程的runloop在app启动时已经配置好了,并且已经启动。

所以只有分线程中才需要自己配置并启动runloop。方式就是获取这个线程的runloop,启动它,并配置所有时间的处理函数。


线程见通信

最好的线程间不要通信,各干各的,但通常这是不可能的。这个表里面列出了一些常用的通信方式



设计时一些谨记的要点:

1、尽量避免显示的创建线程

原因很简单。Writing thread-creation code manually is tedious and potentially error-prone and you should avoid it whenever possible。

这种方式很累,而且容易出错,所以只要可以尽量不要自己创建线程。

2、保持线程繁忙

因为线程是有开销的,不要无故的创建很多线程

3、避免线程间共享数据

原因是需要对共享资源进行同步

4、关系到界面刷新的任务,要在主线程中做。

5、要注意线程退出的行为。

6、异常处理

7、干净的结束线程

最好的方式就是让线程运行完毕自然退出。但是通常会需要在线程没有结束时需要退出,这很可能造成线程打开的资源没有释放,例如

内存或者打开的文件等。所以如何干净的退出线程,也是值得注意的。

Setting the Thread Priority

优先级使用默认就行了

Creating an Autorelease Pool

如何使用runloop

When writing code you want to run on a separate thread, you have two options. The first option is to write the code for a thread as one long task to be performed with little or no interruption, and have the thread exit when it finishes. The second option is put your thread into a loop and have it process requests dynamically as they arrive. The first option requires no special setup for your code; you just start doing the work you want to do. The second option, however, involves setting up your thread’s run loop.(熟读理解)

如果是一个直接的无需打断的任务,不需要runloop,但线程中如果需要周期性的处理一些事件,就需要启动一个runloop

这就是为什么主线程会启动一个默认runloop,但是分线程没有。因为主线程需要不断地响应用户的操作。

Terminating a Thread

有关退出线程的这部分非常重要

If you anticipate the need to terminate a thread in the middle of an operation, you should design your threads from the outset to respond to a cancel or exit message. For long-running operations, this might mean stopping work periodically and checking to see if such a message arrived. If a message does come in asking the thread to exit, the thread would then have the opportunity to perform any needed cleanup and exit gracefully; otherwise, it could simply go back to work and process the next chunk of data

这部分内容非常重要,背诵!很多bug就是没有处理好线程退出导致的。


原创粉丝点击