GCD(Grand Central Dispatch)是異步執行任務的技術之一。它把原本要寫在應用層的線程管理程式碼下沉到系統層:開發者只需定義想執行的任務,把它追加到合適的 Dispatch Queue,GCD 就會自動建立所需線程並排定執行順序。由於線程管理由系統統一負責,調度效率比過去自行管理更高。
顧名思義,Dispatch Queue 就是執行處理的等待隊列,按追加順序取出處理,遵循先進先出(FIFO)。
Serial Dispatch Queue:序列化隊列,會等待目前執行的處理結束。
Concurrent Dispatch Queue:並行隊列,不等待目前執行的處理結束。
用一段同步追加來比較兩者:
dispatch_sync(queue, block1); dispatch_sync(queue, block2); dispatch_sync(queue, block3); dispatch_sync(queue, block4); dispatch_sync(queue, block5); dispatch_sync(queue, block6);
若 queue 是串行隊列:block1 執行完才轮到 block2,block2 執行完才轮到 block3,以此類推,同時執行的處理數只有一個。
block1 → block2 → block3 → block4 → block5 → block6
若 queue 是並行隊列:block1 開始後,不管它有沒有結束,block2 就接著啟動;block2 還沒結束,block3 也啟動了,如此循環。同時執行的數量取決於當前系統狀態。
線程1/線程2/線程3 分別承載 block1、block2、block3……block4、block5、block6。
第一種:dispatch_queue_create
// 建立串行隊列
dispatch_queue_t queue = dispatch_queue_create("com.baidu.queue", DISPATCH_QUEUE_SERIAL);
// 建立並行隊列
dispatch_queue_t queue = dispatch_queue_create("com.baidu.queue", DISPATCH_QUEUE_CONCURRENT);
用 dispatch_queue_create 可以建立任意多個 Dispatch Queue。要注意的是:多個串行隊列之間是可以並行執行的,只是每個串行隊列內部同時只能跑一個追加進去的處理。
自行建立的隊列在使用完畢後需要釋放:
dispatch_release(queue);
第二種:取得系統標準提供的隊列。
Main Dispatch Queue 是在主線程執行的串行隊列:
dispatch_queue_t mainQueue = dispatch_get_main_queue();
追加到主隊列的處理會在主線程的 RunLoop 中執行,因此所有必須在主線程完成的工作(例如更新 UI)都該放進主隊列,效果等同 performSelectorOnMainThread。
Global Dispatch Queue 是並行隊列,所有應用都能使用,不需要自己一個個建立:
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
第一個參數是優先級,共四檔:
#define DISPATCH_QUEUE_PRIORITY_HIGH 2 #define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 #define DISPATCH_QUEUE_PRIORITY_LOW (-2) #define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN
GCD 提供兩種執行方式:
// 同步 dispatch_sync(dispatch_queue_t queue, dispatch_block_t block); // 異步 dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
兩者的差別:同步只能在當前線程執行任務,不具備開啟新線程的能力;異步可以在新線程執行任務,具備開啟新線程的能力。
不會開啟新線程,在當前線程執行任務,且任務依序執行。
- (void)syncSerial {
NSLog(@"syncSerial ----- begin");
dispatch_queue_t serialQueue = dispatch_queue_create("com.vn.serial", NULL);
dispatch_sync(serialQueue, ^{ NSLog(@"1...sync....%@", [NSThread currentThread]); });
dispatch_sync(serialQueue, ^{ NSLog(@"2...sync....%@", [NSThread currentThread]); });
dispatch_sync(serialQueue, ^{ NSLog(@"3...sync....%@", [NSThread currentThread]); });
NSLog(@"syncSerial ----- end");
}
輸出:begin → 1 → 2 → 3 → end,全部落在 main 線程(number = 1)。
會開啟新線程,但任務依然串行。
- (void)asyncSerial {
NSLog(@"asyncSerial ----- begin");
dispatch_queue_t serialQueue = dispatch_queue_create("com.vn.serial", NULL);
dispatch_async(serialQueue, ^{ NSLog(@"1...async....%@", [NSThread currentThread]); });
dispatch_async(serialQueue, ^{ NSLog(@"2...async....%@", [NSThread currentThread]); });
dispatch_async(serialQueue, ^{ NSLog(@"3...async....%@", [NSThread currentThread]); });
NSLog(@"asyncSerial ----- end");
}
輸出:begin → end → 1 → 2 → 3,三個任務都在同一條子線程(number = 3)上依序執行。
// 死鎖,不應該這樣用
- (void)syncMain {
NSLog(@"syncMain ----- begin");
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_sync(mainQueue, ^{ NSLog(@"1--syncMain---%@", [NSThread currentThread]); });
NSLog(@"syncMain ----- end");
}
只會輸出 syncMain ----- begin 之後就卡死。
在主線程執行任務,不會阻塞主線程,任務依序執行。
- (void)asyncMain {
NSLog(@"asyncMain ----- begin");
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{ NSLog(@"1--asyncMain---%@", [NSThread currentThread]); });
dispatch_async(mainQueue, ^{ NSLog(@"2--asyncMain---%@", [NSThread currentThread]); });
dispatch_async(mainQueue, ^{ NSLog(@"3--asyncMain---%@", [NSThread currentThread]); });
NSLog(@"asyncMain ----- end");
}
輸出:begin → end → 1 → 2 → 3,全部在 main 線程。
不會開啟新線程;由於不會開新線程,必須等目前任務跑完,所以看起來仍是依序執行。
- (void)syncConcurrent {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{ NSLog(@"1--syncConcurrent---%@", [NSThread currentThread]); });
dispatch_sync(queue, ^{ NSLog(@"2--syncConcurrent---%@", [NSThread currentThread]); });
dispatch_sync(queue, ^{ NSLog(@"3--syncConcurrent---%@", [NSThread currentThread]); });
NSLog(@"syncConcurrent--------end");
}
輸出:1 → 2 → 3 → end,全部在 main 線程。
可以同時開啟多條線程。
- (void)asyncConcurrent {
NSLog(@"asyncConcurrent--------begin");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{ NSLog(@"1--asyncConcurrent---%@", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"2--asyncConcurrent---%@", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"3--asyncConcurrent---%@", [NSThread currentThread]); });
NSLog(@"asyncConcurrent--------end");
}
輸出:begin → end → 1、2、3 分散在 number = 3、4、5 三條不同線程上,順序不固定。
- (void)threadCommunication {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"https://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主線程更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
});
}
- (void)delay {
NSLog(@"delay-----begin");
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^{
NSLog(@"after------%@", [NSThread currentThread]);
});
NSLog(@"delay-----end");
}
輸出:begin → end →(約 1 秒後)after。
要特別注意:dispatch_after 並不是「延遲指定時間後執行」,而是「延遲指定時間後才把任務追加到隊列」。時間計算寫法如下:
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC); dispatch_time_t time1 = dispatch_time(DISPATCH_TIME_NOW, 1000ull * NSEC_PER_MSEC); dispatch_time_t time2 = dispatch_time(DISPATCH_TIME_NOW, 1000ull * USEC_PER_SEC);
相關常量:
#define NSEC_PER_SEC 1000000000ull // 一秒有多少納秒 #define NSEC_PER_MSEC 1000000ull // 一毫秒有多少納秒 #define USEC_PER_SEC 1000000ull // 一秒有多少微秒 #define NSEC_PER_USEC 1000ull // 一微秒有多少納秒
常見需求:執行多個任務,等這幾個任務全部完成後,再執行最終的收尾任務。這時可以用 Dispatch Group。
- (void)group {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
for (int i = 0; i < 5; i++) { NSLog(@"任務1--------%d", i); }
});
dispatch_group_async(group, queue, ^{
for (int i = 0; i < 5; i++) { NSLog(@"任務2--------%d", i); }
});
dispatch_group_notify(group, queue, ^{
NSLog(@"end.....");
});
}
輸出中兩個任務交錯執行,最後才印出 end,順序由系統調度決定。
在存取資料庫或檔案時,寫入處理不能與其他寫入、也不能與讀寫並存的處理同時執行;但讀取彼此之間並行是安全的。
為了兼顧效率與正確性,常見做法是:讀取任務追加到並行隊列,寫入任務則在沒有任何讀取進行時獨佔執行。用 Dispatch Group 加 dispatch_set_target_queue 也能做到,但會複雜很多。GCD 提供了更簡便的 dispatch_barrier_async。
- (void)barrier {
dispatch_queue_t queue = dispatch_queue_create("abcd", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{ NSLog(@"----1-----%@", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"----2-----%@", [NSThread currentThread]); });
dispatch_barrier_async(queue, ^{ NSLog(@"----barrier-----%@", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"----3-----%@", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"----4-----%@", [NSThread currentThread]); });
}
執行結果:任務1、2 完成後,barrier 才追加進隊列並獨佔執行;barrier 結束後,任務3、4 才開始。
按指定次數把 block 追加到隊列,並等待全部執行結束。
- (void)apply {
NSLog(@"apply------begin");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"apply------%zu", index);
});
NSLog(@"apply------end");
}
輸出中 0~9 分散在多條線程,全部完成後才印 end。它也常用來遍歷陣列:
dispatch_apply([array count], queue, ^(size_t index) {
// 處理 array[index]
});
由於 dispatch_apply 和 dispatch_sync 一樣會等待處理結束,實務上建議把它放進 dispatch_async 裡異步執行,避免阻塞當前線程:
- (void)apply1 {
NSLog(@"apply1------begin");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
dispatch_apply(5, queue, ^(size_t index) {
NSLog(@"apply------%zu", index);
});
dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"done"); });
});
NSLog(@"apply1------end");
}
保證整段程式碼在應用生命週期內只執行一次,常用於單例。
- (void)once {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"------run");
});
}