gpt4 book ai didi

ios - 不遵循 QoS 优先级的队列

转载 作者:搜寻专家 更新时间:2023-11-01 07:16:53 27 4
gpt4 key购买 nike

问题:当关注这个 tutorial 时,我为 2 个队列分配了不同的 QoS。但是,当我运行代码时,队列表现得好像它们具有相同的优先级。此外,即使先调用红点,蓝点也会在红点之前打印。我在 completed project 上运行了代码由教程提供。

注意:有一次,当我在模拟器上删除应用程序并重新运行应用程序时,我得到了一个output。这与教程非常接近。但是再次运行代码后,我得到了下面的输出。即使再次删除并重新运行该应用程序,也只会给我相同的输出。

代码

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
queuesWithQoS()
}

func queuesWithQoS() {
let queue1 = DispatchQueue(label: "com.appcoda.queue1", qos: DispatchQoS.userInitiated)
let queue2 = DispatchQueue(label: "com.appcoda.queue2", qos: DispatchQoS.utility)

queue1.async {
for i in 0..<10 {
print("🔴", i)
}
}

queue2.async {
for i in 100..<110 {
print("🔵", i)
}
}
}

我的输出:

enter image description here

教程的输出:

enter image description here

最佳答案

这是一个结构相当糟糕的教程。我建议这样重写:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
queuesWithQoS()
}
let queue1 = DispatchQueue(label: "com.appcoda.queue1", qos: .userInitiated)
let queue2 = DispatchQueue(label: "com.appcoda.queue2", qos: .utility)
func queuesWithQoS() {
queue1.async {
for i in 0..<10 {
NSLog("%@ %d", "🔴", i)
}
}
queue2.async {
for i in 100..<110 {
NSLog("%@ %d", "🔵", i)
}
}
}

我做了两个改变:

  • 我已经赋予队列持久性,将它们具体化为实例属性而不是本地属性;

  • 并且我使用了 NSLog 而不是 print,因为众所周知 print 不是线程安全的,所以正是这样您正在尝试学习的正是您无法准确学习的内容。

当我构建并运行时,我反复得到这样的信息:

2017-01-16 10:41:25.577 qosTest[3033:285702] 🔴 0
2017-01-16 10:41:25.577 qosTest[3033:285703] 🔵 100
2017-01-16 10:41:25.579 qosTest[3033:285702] 🔴 1
2017-01-16 10:41:25.579 qosTest[3033:285702] 🔴 2
2017-01-16 10:41:25.580 qosTest[3033:285702] 🔴 3
2017-01-16 10:41:25.579 qosTest[3033:285703] 🔵 101
2017-01-16 10:41:25.580 qosTest[3033:285702] 🔴 4
2017-01-16 10:41:25.580 qosTest[3033:285702] 🔴 5
2017-01-16 10:41:25.580 qosTest[3033:285703] 🔵 102
2017-01-16 10:41:25.581 qosTest[3033:285702] 🔴 6
2017-01-16 10:41:25.581 qosTest[3033:285702] 🔴 7
2017-01-16 10:41:25.581 qosTest[3033:285703] 🔵 103
2017-01-16 10:41:25.581 qosTest[3033:285702] 🔴 8
2017-01-16 10:41:25.582 qosTest[3033:285702] 🔴 9
2017-01-16 10:41:25.585 qosTest[3033:285703] 🔵 104
2017-01-16 10:41:25.586 qosTest[3033:285703] 🔵 105
2017-01-16 10:41:25.610 qosTest[3033:285703] 🔵 106
2017-01-16 10:41:25.611 qosTest[3033:285703] 🔵 107
2017-01-16 10:41:25.613 qosTest[3033:285703] 🔵 108
2017-01-16 10:41:25.615 qosTest[3033:285703] 🔵 109

这似乎更现实:我们更喜欢一个线程而不是另一个线程,但我们不会独占运行一个线程而不是另一个线程。我建议本教程的结果(可能还有您的结果)只是粗心编码的产物。

关于ios - 不遵循 QoS 优先级的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com