考虑这段微不足道的代码
DispatchQueue.global().async {
print("2")
}
print("1")
我们可以说输出如下:
1
2
在什么情况下执行顺序会有所不同(不考虑使用的队列类型)?如果有的话,他们是否可以强制手动出现?
最佳答案
你说:
we can say that output will be as following ...
不,充其量你只能说输出会经常/频繁地按照那个顺序,但不能保证是这样。
该代码片段将代码异步分派(dispatch)到全局并发队列,该队列将在单独的工作线程上运行它,并且在没有任何同步的情况下,当前线程和该工作线程之间存在典型的竞争条件.您无法保证这些 print
语句的顺序,但在实践中,您经常会在 2
之前看到 1
。
this is one of the common questions at tech interview; and for some reason interviewers expect conclusion that order of execution is constant here. So (as it was not aligned with my understanding) I decided to clarify.
你的理解是正确的,这两个print
语句的顺序是肯定不能保证的。
Are there any circumstances under which order of execution will be different
几个想法:
例如,通过调整队列优先级,您可以更改
1
出现在2
之前的可能性。但是,同样,不能保证。有多种机制可以保证顺序。
- 您可以使用串行队列……我了解到您不想考虑使用另一个/不同的队列,但它通常是正确的解决方案,因此如果没有这种情况,关于该主题的任何讨论都是不完整的;<
- 可以使用dispatch group ...当当前队列满足group时可以在全局队列上
通知
; - 您可以使用调度信号量……信号量是该问题的经典答案,但恕我直言,信号量应谨慎使用,因为它很容易出错……而且阻塞线程从来都不是一个好主意;
- 为了完整起见,我们应该提到您确实可以使用任何 synchronization机制,例如锁。
关于Swift 调度队列异步执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54980780/