Grand Central Dispatch(GCD)是蘋果提供的非同步任務執行技術。它把原本需要開發者手動管理的執行緒相關程式碼下沉到系統層級實作,開發者只要定義想執行的任務並追加到合適的 Dispatch Queue,GCD 就會自動生成所需執行緒並排程執行。由於執行緒由系統統一管理,效率遠優於以往的手動方式。
Dispatch Queue 是執行任務的隊列,也是 GCD 最基本的元素,分為兩種:
取得 Dispatch Queue 有兩種方式。第一種是自己創建:
let myQueue: dispatch_queue_t = dispatch_queue_create("com.xxx", nil)
第一個參數是隊列名稱,建議使用反序的網域名稱以便除錯;第二個參數為 nil 時回傳 Serial Queue,指定為 DISPATCH_QUEUE_CONCURRENT 時回傳 Concurrent Queue。
需要注意的是,在 OS X 10.8 或 iOS 6 及之後版本中,Dispatch Queue 會由 ARC 自動管理;在更早的版本中則需手動釋放:
dispatch_async(myQueue, { () -> Void in
println("in Block")
})
dispatch_release(myQueue)
第二種方式是直接取得系統提供的 Dispatch Queue,主要分為兩類:
通常只有在需要更新 UI 時才取得 Main Queue,其他情況用 Global Queue 即可:
// 獲取Main Dispatch Queue let mainQueue = dispatch_get_main_queue() // 獲取Global Dispatch Queue let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
它能讓加入隊列的任務延遲執行,例如讓一個 Block 在 10 秒後執行:
var time = dispatch_time(DISPATCH_TIME_NOW, (Int64)(10 * NSEC_PER_SEC))
dispatch_after(time, globalQueue) { () -> Void in
println("在10秒後執行")
}
NSEC_PER_SEC 表示秒數,另有 NSEC_PER_MSEC 表示毫秒。嚴格來說,dispatch_after 的含義是「在 10 秒後把任務加入隊列」,並非保證 10 秒後精準執行,只有在對時間要求極高的場景才可能出問題。
取得 dispatch_time_t 有 dispatch_time(相對時間)與 dispatch_walltime(絕對時間)兩種方式。以下是一個把 NSDate 轉為 dispatch_time_t 的 Swift 方法:
func getDispatchTimeByDate(date: NSDate) -> dispatch_time_t {
let interval = date.timeIntervalSince1970
var second = 0.0
let subsecond = modf(interval, &second)
var time = timespec(tv_sec: __darwin_time_t(second), tv_nsec: (Int)(subsecond * (Double)(NSEC_PER_SEC)))
return dispatch_walltime(&time, 0)
}
當我們有多個 Block 要執行,不在意順序,只想在它們全部完成後再執行某個操作時,就可以使用 dispatch_group:
let group = dispatch_group_create()
dispatch_group_async(group, globalQueue) { () -> Void in println("1") }
dispatch_group_async(group, globalQueue) { () -> Void in println("2") }
dispatch_group_async(group, globalQueue) { () -> Void in println("3") }
dispatch_group_notify(group, globalQueue) { () -> Void in println("completed") }
輸出順序與加入順序無關,但 "completed" 一定在最後。除了 dispatch_group_notify,也可以用 dispatch_group_wait:
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
println("completed")
注意 dispatch_group_wait 會使當前執行緒進入等待;若在主執行緒呼叫,上面的 Block 完成前主執行緒會卡住。第二個參數可指定超時時間,並透過返回值判斷是完成還是超時。
顧名思義,它在隊列中插入一道「柵欄」:在它之前已開始的 Block 會繼續執行,當它開始執行時其他 Block 進入等待,它執行完後後續 Block 才繼續。適合用於讀寫並存的情境,避免寫入時被讀取:
dispatch_async(globalQueue) { self.readFile() }
dispatch_async(globalQueue) { self.readFile() }
dispatch_barrier_async(globalQueue) { self.writeFile() ; self.readFile() }
dispatch_async(globalQueue) { self.readFile() }
它會將指定的 Block 執行指定的次數,非常適合對陣列所有元素套用相同操作:
dispatch_apply(10, globalQueue) { (index) -> Void in
print(index)
}
print("completed")
由於 dispatch_apply 是同步的,會使執行緒在此等待,因此一般應在非同步執行緒中使用它:
dispatch_async(globalQueue, { () -> Void in
dispatch_apply(10, globalQueue) { (index) -> Void in
print(index)
}
print("completed")
})
print("在dispatch_apply之前")
某些情況下,我們可能想讓 Dispatch Queue 暫時停止,之後再恢復:
dispatch_suspend(globalQueue) // 暫停 dispatch_resume(globalQueue) // 恢復
暫停時,若已有 Block 正在執行則不受影響,dispatch_suspend 只對尚未開始的 Block 生效。
信號量在多執行緒開發中被廣泛使用:進入關鍵程式碼前必須取得信號量,完成後釋放。當計數大於 0 時,每個進來的執行緒使計數減 1,直到變為 0;此後其他執行緒進入等待,直到有執行緒釋放信號使計數加 1。以下例子啟動 10 條執行緒,但同時只有一條能執行:
let semaphore = dispatch_semaphore_create(1)
for i in 0 ... 9 {
dispatch_async(globalQueue, { () -> Void in
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
let time = dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC))
dispatch_after(time, globalQueue) { () -> Void in
print("2秒後執行")
dispatch_semaphore_signal(semaphore)
}
})
}
透過 dispatch_semaphore_create 初始化並指定初值,dispatch_semaphore_wait 取得信號並使計數減 1,dispatch_semaphore_signal 釋放信號並使計數加 1。wait 同樣支援超時設定。
dispatch_once 通常用於單例模式,可保證某段程式碼在程式運行期間只執行一次:
class SingletonObject {
class var sharedInstance : SingletonObject {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : SingletonObject? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SingletonObject()
}
return Static.instance!
}
}
掌握以上這些 GCD 元件,就能在多執行緒開發中游刃有餘,既高效又安全。