本文整理自 WWDC2010 Session 211,主題是「使用 Grand Central Dispatch(GCD)簡化 iPhone 開發」,作者為 Core OS 團隊的 Daniel Steffen。以下按主題歸納 GCD 的核心概念與用法。
加鎖的目的是對關鍵資源進行互斥訪問,確保在多執行緒環境下按序訪問共享資源、保證數據完整性。對比傳統加鎖與 GCD 的寫法:
沒有 GCD 的傳統寫法(使用 NSLock):
- (void)updateImageCacheWithImg:(UIImage*)img {
NSLock *l = self.imageCacheLock;
[l lock];
// 關鍵區段
if ([self.imageCache containsObj:img]) {
[l unlock]; // 別忘了要解鎖
return;
}
[self.imageCache addObj:img];
[l unlock];
}
使用 GCD 的寫法:
- (void)updateImageCacheWithImg:(NSImage*)img {
dispatch_queue_t queue = self.imageCacheQueue;
dispatch_sync(queue, ^{ // 改成 dispatch_async 可延後執行關鍵區段
// 關鍵區段
if ([self.imageCache containsObj:img]) {
return;
}
[self.imageCache addObj:img];
});
}
傳統方式包括 performSelectorOnMainThread:withObject:waitUntilDone:、performSelector:onThread:withObject:waitUntilDone:、performSelector:withObject:afterDelay:、performSelectorInBackground:withObject: 等。GCD 提供了等價的寫法:
// 等同於 performSelector:onThread:withObject:waitUntilDone: NO
dispatch_async(queue, ^{
[myObject doSomething:foo withData:bar];
});
// waitUntilDone: YES
dispatch_sync(queue, ^{
[myObject doSomething:foo withData:bar];
});
// 等同於 performSelector:withObject:afterDelay:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 50000 /* 50μs */);
dispatch_after(delay, queue, ^{
[myObject doSomething:foo withData:bar];
});
// 等同於 performSelectorInBackground:withObject:
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
[myObject doSomething:foo withData:bar];
});
原始影片中還有關於 Dispatch Sources、Source Cancellation、Target Queues 的深入探討,有興趣者可參考原始影片。
總體而言,GCD 透過「佇列 + block」的模型,把複雜的執行緒管理交由系統統一調度,讓開發者能以更簡潔的程式碼實現高效、安全的並發編程。