當我運行下面的操場我注意到默認調度隊列似乎是叫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和非串行隊列(併發)使用隨機執行標準,那麼將無法完成定製任務。) –