工作閑聊
偶爾偷偷懶和群內(nèi)各位iOS大佬吹吹逼读拆,這不來了個多線程相關(guān)的問題镣奋。
源于閑聊時對自己的懷疑枪汪。
Q:主線程的優(yōu)先級是不是最高的?
A:當(dāng)我看到問題時的回答:是世澜。
優(yōu)先級
線程優(yōu)先級決定了任務(wù)開始執(zhí)后系統(tǒng)資源分配的優(yōu)先級独旷,例如 CPU 時間片, 網(wǎng)絡(luò)資源, 硬盤資源等。
typedef NS_ENUM(NSInteger, NSQualityOfService) {
NSQualityOfServiceUserInteractive = 0x21,
NSQualityOfServiceUserInitiated = 0x19,
NSQualityOfServiceUtility = 0x11,
NSQualityOfServiceBackground = 0x09,
NSQualityOfServiceDefault = -1
};
- NSQualityOfServiceUserInteractive:用來處理用戶操作寥裂,例如界面刷新嵌洼、動畫等。優(yōu)先級最高封恰,即時執(zhí)行麻养。
- NSQualityOfServiceUserInitiated:處理初始化任務(wù),為將來的用戶操作作準(zhǔn)備诺舔。例如加載文件或 Email 等鳖昌”钙瑁基本即時執(zhí)行,最多幾秒延遲遗遵。
- NSQualityOfServiceUtility:用戶不需要立即結(jié)果的操作萍恕,一般伴隨進(jìn)度條逸嘀。例如下載车要、數(shù)據(jù)導(dǎo)入、周期性的內(nèi)容更新等崭倘。幾秒到幾分鐘延遲翼岁。
- NSQualityOfServiceBackground:用于用戶不可見的操作。例如簡歷索引司光、預(yù)加載琅坡、同步等。幾分鐘到數(shù)小時延遲残家。
- NSQualityOfServiceDefault:默認(rèn)的 QoS 用來表示缺省值榆俺。當(dāng)有可能通過其它途徑推斷出可能的 QoS 信息時,則使用推斷出的 Qos坞淮。如果不能推斷茴晋,則使用 UserInitiated 和 Utility 之間的 QoS。
測試
NSThread *currentThread = [NSThread mainThread];
NSLog(@"%ld", (long)currentThread.qualityOfService);
此時經(jīng)過上面的分析確實應(yīng)該是最高的回窘,但難道是錯的嗎诺擅?
后面查了官方文檔有如下一段話:
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.
你創(chuàng)建的任何新線程都有一個與之關(guān)聯(lián)的默認(rèn)優(yōu)先級。內(nèi)核調(diào)度算法在決定該運(yùn)行哪個線程時啡直,會把線程的優(yōu)先級作為考量因素烁涌,較高優(yōu)先級的線程會比較低優(yōu)先級的線程具有更多的運(yùn)行機(jī)會。較高優(yōu)先級不保證你的線程具體執(zhí)行的時間酒觅,只是相比較低優(yōu)先級的線程撮执,它更有可能被調(diào)度器選擇執(zhí)行而已。
下面還有個重要提示:
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.
重要提示:通常最好將線程的優(yōu)先級保留為其默認(rèn)值舷丹。增加一些線程的優(yōu)先級也會增加低優(yōu)先級線程中出現(xiàn)饑餓的可能性二打。如果應(yīng)用程序包含必須相互交互的高優(yōu)先級和低優(yōu)先級線程,則低優(yōu)先級線程的匱乏可能會阻塞其他線程并造成性能瓶頸掂榔。
此時我覺得出題的那位同學(xué)問題不夠嚴(yán)謹(jǐn)继效,又或者沒有g(shù)et到他的點,然而后續(xù)也聯(lián)系不到那位同學(xué)装获,所以只能告一段落瑞信。