gpt4 book ai didi

swift - swift 3 中调度队列的优先级

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:02 25 4
gpt4 key购买 nike

我已经阅读了关于 GCD and Dispatch Queue in Swift 3 的教程

但是对于同步执行和异步执行的顺序以及主队列和后台队列,我真的是一头雾水。

我知道,如果我们使用sync,那么如果我们使用async,我们就会一个接一个地执行它们strong> 那么我们可以使用QoS 来设置它们的优先级,但是这种情况呢?

func queuesWithQoS() {
let queue1 = DispatchQueue(label: "com.appcoda.myqueue1")
let queue2 = DispatchQueue(label: "com.appcoda.myqueue2")

for i in 1000..<1005 {
print(i)
}


queue1.async {
for i in 0..<5{
print(i)
}
}

queue2.sync {
for i in 100..<105{
print( i)
}
}
}

enter image description here

结果表明我们忽略了异步执行。我知道 queue2 应该在 queue1 之前完成,因为它是同步执行的,但是为什么我们忽略异步执行并且异步、同步和所谓的主队列之间的实际区别是什么?

最佳答案

你说:

The outcome shows that we ignore the asynchronous execution. ...

不,这只是意味着您没有给异步调度代码足够的时间来开始。

I know queue2 should be completed before queue1 since it's synchronous execution ...

首先,queue2 可能不会在 queue1 之前完成。它只是碰巧。让 queue2 做一些更慢的事情(例如循环几千次迭代而不是仅仅五次)你会看到 queue1 实际上可以与 queue2 上的内容同时运行。只需几毫秒即可开始,非常简单的 queue2 上的内容在 queue1 上的内容有机会开始之前完成。

其次,这种行为在技术上不是因为它是同步执行。只是异步需要几毫秒才能在某个工作线程上运行它的东西,而同步调用,因为我不会让你厌烦的优化,启动得更快。

but why we ignore the asynchronous execution ...

我们不会“忽略”它。只需几毫秒即可开始。

and what is the actual difference between async, sync and so-called main queue?

“异步”仅表示当前线程可以继续运行,而不是等待分派(dispatch)的代码在其他线程上运行。 “Sync”意味着当前线程应该等待分派(dispatch)的代码完成。

“主线程”是一个不同的主题,它只是指为驱动 UI 而创建的主线程。实际上,主线程是大部分代码运行的地方,基本上运行除了您手动分派(dispatch)到某个后台队列(或为您分派(dispatch)的代码,例如 URLSession 完成处理程序)之外的所有内容。

关于swift - swift 3 中调度队列的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025848/

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