一次閒聊引申對執行緒優先順序的思考
工作閒聊
偶爾偷偷懶和群內各位iOS大佬吹吹逼,這不來了個多執行緒相關的問題。

一次群聊
源於閒聊時對自己的懷疑。
Q:主執行緒的優先順序是不是最高的?
A:當我看到問題時的回答:是。
優先順序
執行緒優先順序決定了任務開始執後系統資源分配的優先順序,例如 CPU 時間片, 網路資源, 硬碟資源等。
typedef NS_ENUM(NSInteger, NSQualityOfService) { NSQualityOfServiceUserInteractive = 0x21, NSQualityOfServiceUserInitiated = 0x19, NSQualityOfServiceUtility = 0x11, NSQualityOfServiceBackground = 0x09, NSQualityOfServiceDefault = -1 };
- NSQualityOfServiceUserInteractive:用來處理使用者操作,例如介面重新整理、動畫等。優先順序最高,即時執行。
- NSQualityOfServiceUserInitiated:處理初始化任務,為將來的使用者操作作準備。例如載入檔案或 Email 等。基本即時執行,最多幾秒延遲。
- NSQualityOfServiceUtility:使用者不需要立即結果的操作,一般伴隨進度條。例如下載、資料匯入、週期性的內容更新等。幾秒到幾分鐘延遲。
- NSQualityOfServiceBackground:用於使用者不可見的操作。例如簡歷索引、預載入、同步等。幾分鐘到數小時延遲。
- NSQualityOfServiceDefault:預設的 QoS 用來表示預設值。當有可能通過其它途徑推斷出可能的 QoS 資訊時,則使用推斷出的 Qos。如果不能推斷,則使用 UserInitiated 和 Utility 之間的 QoS。
測試
NSThread *currentThread = [NSThread mainThread]; NSLog(@"%ld", (long)currentThread.qualityOfService);
此時經過上面的分析確實應該是最高的,但難道是錯的嗎?
後面查了官方文件有如下一段話:
Setting the Thread PriorityAny 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到他的點,然而後續也聯絡不到那位同學,所以只能告一段落。