我遇到的问题是为什么以下代码打印出来的优先级是一样的?为什么是这样?非常感谢你。
print("main:\(Thread.current)")
print("thread main priorities:\(Thread.current.threadPriority)")
DispatchQueue.global(qos: .utility).async {
print("utility:\(Thread.current)")
print("thread utility priorities:\(Thread.current.threadPriority)")
}
DispatchQueue.global(qos: .background).async {
print("background:\(Thread.current)")
print("thread background priorities:\(Thread.current.threadPriority)")
}
DispatchQueue.global(qos: .userInteractive).async {
print("userInteractive:\(Thread.current)")
print("thread userInteractive priorities:\(Thread.current.threadPriority)")
}
DispatchQueue.global(qos: .userInitiated).async {
print("userInitiated:\(Thread.current)")
print("thread userInitiated priorities:\(Thread.current.threadPriority)")
}
日志:
main:{number = 1,name = main} 主要优先事项:0.5
userInteractive:{number = 3,name =(null)}
实用程序:{number = 5,name =(null)}
background:{number = 6,name =(null)}
thread userInteractive priority:0.5
userInitiated:{number = 4,name =(null)}
线程实用程序优先级:0.5
线程后台优先级:0.5
线程userInitiated priority:0.5
答案 0 :(得分:1)
正如您在文档中看到的那样:
@available(iOS 4.0, *)
open var threadPriority: Double // To be deprecated; use qualityOfService below
不推荐使用threadPriority。此外,Apple的GCD团队对Thread-Queue主题非常清楚。 GCD将为您管理线程。队列优先级不是线程优先级。看一下这个例子,这是你在这里发布的代码,我刚刚添加了" qos_class_self()。rawValue",这实际上是你应该如何测试QoS,而不是& #34; threadPriority"
print("main:\(Thread.current), Thread main priorities:\(Thread.current.threadPriority), QoS: \(qos_class_self().rawValue)")
DispatchQueue.global(qos: .utility).async {
print("utility:\(Thread.current), Thread utility priorities:\(Thread.current.threadPriority), QoS: \(qos_class_self().rawValue)")
}
DispatchQueue.global(qos: .background).async {
print("background:\(Thread.current), Thread background priorities:\(Thread.current.threadPriority), QoS: \(qos_class_self().rawValue)")
}
DispatchQueue.global(qos: .userInteractive).async {
print("userInteractive:\(Thread.current), Thread userInteractive priorities:\(Thread.current.threadPriority), QoS: \(qos_class_self().rawValue)")
}
DispatchQueue.global(qos: .userInitiated).async {
print("userInitiated:\(Thread.current), Thread userInitiated priorities:\(Thread.current.threadPriority), QoS: \(qos_class_self().rawValue)")
}
我还合并了每个封闭的打印件,因此它们不会在日志中的不同行中被打乱。这表明维护了QoS,而不推荐使用threadPriority。
main:<NSThread: 0x6100000762c0>{number = 1, name = main}, Thread main priorities:0.5, QoS: 33
userInteractive:<NSThread: 0x610000261fc0>{number = 4, name = (null)}, Thread userInteractive priorities:0.5, QoS: 33
utility:<NSThread: 0x618000079100>{number = 3, name = (null)}, Thread utility priorities:0.5, QoS: 17
userInitiated:<NSThread: 0x608000078380>{number = 5, name = (null)}, Thread userInitiated priorities:0.5, QoS: 25
background:<NSThread: 0x610000262000>{number = 6, name = (null)}, Thread background priorities:0.5, QoS: 9
所以,最后,带走的不是思考线程,而是考虑队列,QoS和知道GCD将为您管理线程。与队列出现GCD之前我们习惯的概念截然不同。