一次闲聊引申对线程优先级的思考

工作闲聊

偶尔偷偷懒和群内各位iOS大佬吹吹逼,这不来了个多线程相关的问题。

一次群聊

源于闲聊时对自己的怀疑。

Q:主线程的优先级是不是最高的?

A:当我看到问题时的回答:是。

优先级

线程优先级决定了任务开始执后系统资源分配的优先级,例如 CPU 时间片, 网络资源, 硬盘资源等。

1
2
3
4
5
6
7
typedef NS_ENUM(NSInteger, NSQualityOfService) {
NSQualityOfServiceUserInteractive = 0x21,
NSQualityOfServiceUserInitiated = 0x19,
NSQualityOfServiceUtility = 0x11,
NSQualityOfServiceBackground = 0x09,
NSQualityOfServiceDefault = -1
};
  1. NSQualityOfServiceUserInteractive:用来处理用户操作,例如界面刷新、动画等。优先级最高,即时执行。
  2. NSQualityOfServiceUserInitiated:处理初始化任务,为将来的用户操作作准备。例如加载文件或 Email 等。基本即时执行,最多几秒延迟。
  3. NSQualityOfServiceUtility:用户不需要立即结果的操作,一般伴随进度条。例如下载、数据导入、周期性的内容更新等。几秒到几分钟延迟。
  4. NSQualityOfServiceBackground:用于用户不可见的操作。例如简历索引、预加载、同步等。几分钟到数小时延迟。
  5. NSQualityOfServiceDefault:默认的 QoS 用来表示缺省值。当有可能通过其它途径推断出可能的 QoS 信息时,则使用推断出的 Qos。如果不能推断,则使用 UserInitiated 和 Utility 之间的 QoS。

测试

1
2
NSThread *currentThread = [NSThread mainThread];
NSLog(@"%ld", (long)currentThread.qualityOfService);

此时经过上面的分析确实应该是最高的,但难道是错的吗?

后面查了官方文档有如下一段话:

Setting the Thread Priority
Any new thread you create has a default priority associated with it. The kernel’s scheduling algorithm takes thread priorities into account when determining which threads to run, with higher priority threads being more likely to run than threads with lower priorities. Higher priorities do not guarantee a specific amount of execution time for your thread, just that it is more likely to be chosen by the scheduler when compared to lower-priority threads.

你创建的任何新线程都有一个与之关联的默认优先级。内核调度算法在决定该运行哪个线程时,会把线程的优先级作为考量因素,较高优先级的线程会比较低优先级的线程具有更多的运行机会。较高优先级不保证你的线程具体执行的时间,只是相比较低优先级的线程,它更有可能被调度器选择执行而已。

下面还有个重要提示:

Important: It is generally a good idea to leave the priorities of your threads at their default values. Increasing the priorities of some threads also increases the likelihood of starvation among lower-priority threads. If your application contains high-priority and low-priority threads that must interact with each other, the starvation of lower-priority threads may block other threads and create performance bottlenecks.

重要提示:通常最好将线程的优先级保留为其默认值。增加一些线程的优先级也会增加低优先级线程中出现饥饿的可能性。如果应用程序包含必须相互交互的高优先级和低优先级线程,则低优先级线程的匮乏可能会阻塞其他线程并造成性能瓶颈。

此时我觉得出题的那位同学问题不够严谨,又或者没有get到他的点,然而后续也联系不到那位同学,所以只能告一段落。

参考

Threading Programming Guide: Thread Management