当我运行下面的操场我注意到默认调度队列似乎是叫OS_dispatch_queue_serial一个串行队列。Swift 3:为什么OS_dispatch_queue_serial是默认队列?
这是为什么?
在这种情况下,我对异步和同步语义使用混乱,在这种情况下,他们似乎是同步和连续行为。
我错了吗? 我在混淆与同步的连续?
运行代码之前我期待实现如下:
Hello World
Hello Moon
world * (or Moon)
Moon * (or world)
// Note: here I assumed that async meant that the codes in the block would have been run in parallel to each other and that this would have meant that either world or Moon would have been printed depending on **race conditions**
Hello World
world
Hello Moon
Moon
游乐场代码:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let queue = DispatchQueue(label: "com.test.myqueue")
queue.async {
print("Hello World")
sleep(2)
print("world")
}
queue.async {
print("Hello Moon")
sleep(1)
print("Moon")
}
queue.sync {
print("Hello World")
sleep(2)
print("world")
}
queue.sync {
print("Hello Moon")
sleep(1)
print("Moon")
}
任何帮助了解这更快的将是巨大的。
最初(的iOS 4/OS X 10.6),你不能在GCD创建并发队列。有系统并发队列,但你不能再创建。在iOS 4.3/OS X 10.7中,他们添加了创建并发队列的功能,但将串行队列保留为默认队列。在实践中,我通常很少发现有用的定制并发队列,通常在实现生产者/消费者模式时(https://github.com/iosptl/ios7ptl/blob/master/ch23-AdvGCD/ProducerConsumer/ProducerConsumer/ViewController.m) 。系统通常就足够了。通常当你制作一个自定义队列时,就是序列化访问。 –
(即使我列出的例子并不需要一个自定义的并发队列;对于其中一个系统队列来说也没有问题,所以它比以前更少见:D但是很多使用串行队列的东西都是不可信的如果串行队列使用FIFO和非串行队列(并发)使用随机执行标准,那么将无法完成定制任务。) –