寫 GCD 最怕背概念。其實只要抓住兩個核心——任務(做什麼)與隊列(在哪做),再理解「同步/異步」與「並發/串行」這兩組維度的含義,剩下的組合結論都能自己推出來。
一個生活化的類比:三個人並排走是並發,三個人排成一列依次走是串行;「同步」是自己站在原處等做完,「異步」是分配出去後自己先走。
Grand Central Dispatch,純 C 語言實現,提供了一系列強大的函數。它是蘋果為多核並行運算提出的解法:
使用步驟固定兩步:先定制隊列,再把任務加進去。
// 把右邊的任務提交給左邊的隊列執行
// (1) 同步
dispatch_sync(dispatch_queue_t queue, block);
// (2) 異步
dispatch_async(dispatch_queue_t queue, block);
同步與異步決定要不要開新線程:
並發與串行決定任務的執行方式:
// 串行隊列:隊列名稱 + 隊列屬性(一般傳 NULL)
dispatch_queue_t queue = dispatch_queue_create("Serial Queue", NULL);
// 主隊列:GCD 自帶的特殊串行隊列,任務都在主線程執行
dispatch_queue_t mainQueue = dispatch_get_main_queue();
// 全域並發隊列:系統為每個應用準備好,不需手動建立
// 參數1 為優先級,參數2 為保留參數(傳 0)
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- (void)test1 {
dispatch_queue_t queue = dispatch_queue_create("Serial Queue", NULL);
dispatch_sync(queue, ^{
NSLog(@"下載任務1, curThread = %@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:2];
}); // 這裡會等任務執行完才繼續
NSLog(@"111");
dispatch_sync(queue, ^{
NSLog(@"下載任務2, curThread = %@", [NSThread currentThread]);
});
NSLog(@"222");
dispatch_sync(queue, ^{
NSLog(@"下載圖片任務3, curThread = %@", [NSThread currentThread]);
});
NSLog(@"333");
}
- (void)test2 {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
NSLog(@"下載圖片任務1, curThread = %@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:2];
});
NSLog(@"111");
dispatch_sync(queue, ^{
NSLog(@"下載圖片任務2, curThread = %@", [NSThread currentThread]);
});
NSLog(@"222");
dispatch_sync(queue, ^{
NSLog(@"下載圖片任務3, curThread = %@", [NSThread currentThread]);
});
NSLog(@"333");
}
- (void)test3 {
dispatch_queue_t queue = dispatch_queue_create("Serial Queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"下載圖片任務1, curThread = %@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:2];
});
NSLog(@"1111");
dispatch_async(queue, ^{
NSLog(@"下載圖片任務2, curThread = %@", [NSThread currentThread]);
});
NSLog(@"2222");
dispatch_async(queue, ^{
NSLog(@"下載圖片任務3, curThread = %@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:2];
});
NSLog(@"333");
}
- (void)test4 {
dispatch_queue_t queue = dispatch_queue_create("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"下載圖片任務1, curThread = %@", [NSThread currentThread]);
});
NSLog(@"1111");
dispatch_async(queue, ^{
NSLog(@"下載圖片任務2, curThread = %@", [NSThread currentThread]);
});
NSLog(@"2222");
dispatch_async(queue, ^{
NSLog(@"下載圖片任務3, curThread = %@", [NSThread currentThread]);
});
NSLog(@"333");
}
同步函數不具備開啟線程的能力,無論什麼隊列都不會開線程。
異步函數具備開啟線程的能力,開幾條由隊列決定:串行隊列只開一條,並發隊列會開多條。
凡是函數名帶有 create、copy、new、retain 等字眼的,遵循「誰創建誰釋放」原則,在不使用時要 release。GCD 的數據類型在 ARC 環境下不需要手動 release,但 Core Foundation 的數據類型在 ARC 下仍需自行釋放。