GCD(Grand Central Dispatch)是 Apple 提供的 C 語言併發 API。它最迷人的地方在於:你不再需要親手管理執行緒,只要把「要做的事」交給「佇列」,剩下的交給系統排程。
先看一個完整例子,後面再回頭拆解每個部分。
@interface yxpGCDVController ()
{
UIImageView *_imageView;
}
@end
@implementation yxpGCDVController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"GCD";
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 300, 450)];
_imageView.backgroundColor = [UIColor grayColor];
_imageView.animationDuration = 3.0;
_imageView.animationRepeatCount = 0;
[self.view addSubview:_imageView];
// 丟到背景佇列非同步執行
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *url1 = @"https://h.hiphotos.baidu.com/image/w%3D230/sign=b2d5c289123853438ccf8022a311b01f/91ef76c6a7efce1b1ae9f92fad51f3deb58f6510.jpg";
NSString *url2 = @"https://h.hiphotos.baidu.com/image/pic/item/d058ccbf6c81800aae834e8bb33533fa838b47d5.jpg";
NSString *url3 = @"https://d.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494eec3ba65132ff5e0fe99257e1b.jpg";
NSString *url4 = @"https://g.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa81f4ace4b68f8c5494ee7b1b.jpg";
NSString *url5 = @"https://g.hiphotos.baidu.com/image/pic/item/d6ca7bcb0a46f21f70031fdbf4246b600c33ae07.jpg";
NSArray *array = [[NSArray alloc] initWithObjects:url1, url2, url3, url4, url5, nil];
NSMutableArray *imageArray = [[NSMutableArray alloc] initWithCapacity:20];
for (NSString *string in array) {
NSLog(@"執行圖片下載函數");
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:string]];
UIImage *image = [UIImage imageWithData:data];
[imageArray addObject:image];
}
_imageView.animationImages = imageArray;
// 回到主執行緒更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
[_imageView startAnimating];
});
});
}
@end
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
queue 決定任務交給哪條佇列,block 是你要做的事,而函式名稱開頭的 async/sync 決定「呼叫端要不要等」。
dispatch_async:非同步,呼叫後立刻返回,常用。dispatch_sync:同步,會在該 block 執行完才返回。注意:在主佇列上對主佇列做 sync 會直接死鎖。dispatch_after:延遲執行。dispatch_get_main_queue(),也就是 UI 佇列,所有畫面更新都在這裡做。dispatch_get_global_queue(),由系統建立、有不同優先級,適合放耗時但不影響 UI 的工作。
// 串行佇列
dispatch_queue_t serialQueue = dispatch_queue_create("com.SerialQueue", NULL);
// 並行佇列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.ConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
串行佇列之間彼此還是並行的,但每條串行佇列內部嚴格照順序執行。實務上不要任意大量生產串行佇列;反過來,並行佇列開多一點無妨,因為它背後的執行緒由 XNU 核心統一調度。
單例模式最乾淨的寫法:
static SubObject *subobject = nil;
+ (SubObject *)sharedRequest
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
subobject = [[SubObject alloc] init];
});
return subobject;
}
它同時是執行緒安全的,多條執行緒同時呼叫也只會初始化一次。
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// 兩秒後在主佇列執行
});
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 10; i++) {
NSLog(@"---------%i", i);
}
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
for (int i = 10; i < 20; i++) {
NSLog(@"+++++++++%i", i);
}
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"完成"); // 兩組都跑完才會進來
});
group 是 GCD 相對 NSOperation 額外提供的能力,很適合「同時抓十個介面、全部回來後再合併畫面」這種情境。
一是 block 內對 self 的強引用問題,若該 block 又被子孫物件持有,容易形成循環參考,必要時用 weak 版本斷開。二是不要以為丢進背景佇列就變快了——範例中的同步下載仍然會把該條執行緒佔住,真正的解法是改用非同步的 NSURLSession。