概述
GCD是一個多核編程的解決方案。它主要用於優化應用程序以支持多核處理器。
GCD介紹
要理解GCD的使用就必須先知道GCD中的任務和隊列的概念:
任務
任務即執行操作的意思,換句話說就是你在線程中執行的那段代碼。在 GCD 中是放在 block 中的。執行任務有兩種方式:『同步執行』 和 『異步執行』。兩者的主要區別是:是否等待隊列的任務執行結束,以及是否具備開啓新線程的能力。隊列(Dispatch Queue):
隊列指執行任務的隊列。隊列是一種特殊的線性表,採用 FIFO(先進先出)的原則,即新任務總是被插入到隊列的末尾,而讀取任務的時候總是從隊列的頭部開始讀取。每執行一個任務,則從隊列中釋放一個任務。隊列的結構可參考下圖:
這時候來談GCD的使用就很簡單了,只有兩步:
創建一個隊列(串行隊列或併發隊列);
將任務追加到隊列中,然後系統就會根據隊列類型和任務執行方式執行任務(同步執行或異步執行)。
dispatch_get_specific與dispatch_queue_set_specific
- dispatch_queue_set_specific是向隊列設置一個標識,如:
//向queue1設置一個queueKey1標識
dispatch_queue_set_specific(queue1, queueKey1, &queueKey1,NULL);
- dispatch_get_specific是在當前隊列中取出標識,用來判斷是否當前隊列是標識所在的隊列;
注意iOS中線程和隊列的關係,所有的動作都是在隊列中執行的!
一個簡單的例子:
-(void)testGCD {
static void *queueKey1 = "queueKey1";
dispatch_queue_t queue1 = dispatch_queue_create(queueKey1, DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(queue1, queueKey1, &queueKey1, NULL);
NSLog(@"1. 當前線程是: %@, ",[NSThread currentThread]);
if (dispatch_get_specific(queueKey1)) {
//因爲當前隊列是主隊列,不是queue1隊列,所以取不到queueKey1對應的值,故而不執行
NSLog(@"2. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}else{
NSLog(@"3. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}
dispatch_sync(queue1, ^{
NSLog(@"4. 當前線程是: %@",[NSThread currentThread]);
if (dispatch_get_specific(queueKey1)) {
//當前隊列是queue1隊列,所以能取到queueKey1對應的值,故而執行
NSLog(@"5. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}else{
NSLog(@"6. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}
});
dispatch_async(queue1, ^{
NSLog(@"7. t當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
if (dispatch_get_specific(queueKey1)) {
//當前隊列是queue1隊列,所以能取到queueKey1對應的值,故而執行
NSLog(@"8. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}else{
NSLog(@"9. 當前線程是: %@",[NSThread currentThread]);
[NSThread sleepForTimeInterval:1];
}
});
}
//輸出:
2022-05-25 10:51:56.460219+0800 demo[14026:3587457] 1. 當前線程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main},
2022-05-25 10:51:56.460346+0800 demo[14026:3587457] 3. 當前線程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:57.461678+0800 demo[14026:3587457] 4. 當前線程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:57.461955+0800 demo[14026:3587457] 5. 當前線程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:58.463502+0800 demo[14026:3587541] 7. t當前線程是: <NSThread: 0x283a53840>{number = 3, name = (null)}
2022-05-25 10:51:59.468791+0800 demo[14026:3587541] 8. 當前線程是: <NSThread: 0x283a53840>{number = 3, name = (null)}
這裏解釋一下4的當前線程爲什麼是主線程,因爲串行隊列加同步執行不會產生新線程,直接沿用當前線程也就是主線程。只有串行隊列加異步執行纔會產生新線程,7就證明了這一點。
常見的應用場景
判斷是否在主隊列運行
在 iOS 中,如果我們要判斷代碼是否運行在主線程,可以直接使用NSThread.isMainThread()方法。但如果要判斷是否運行在主隊列(main queue)呢?
需要注意的是,每個應用都只有一個主線程,但主線程中可能有多個隊列,不僅僅只有主隊列,所以 NSThread.isMainThread() 方法並沒有辦法判斷是否是在主隊列運行。而GCD也沒有提供相應的方法。那該如何處理呢?
來看看 React Native 的處理方式:
BOOL RCTIsMainQueue()
{
static void *mainQueueKey = &mainQueueKey;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_queue_set_specific(dispatch_get_main_queue(),
mainQueueKey, mainQueueKey, NULL);
});
return dispatch_get_specific(mainQueueKey) == mainQueueKey;
}
可以看到這裏使用了 dispatch_queue_set_specific 和 dispatch_get_specific 。實際上是通過 dispatch_queue_set_specific 方法給主隊列(main queue)關聯了一個 key-value 對,再通過 dispatch_get_specific 從當前隊列中取出 mainQueueKey 對應的 value。如果是主隊列,取出來的值就是寫入的值,如果是其它主隊列,取出的值就是另一個值或者是 NULL。
當然,同樣可以用類似的方式來設置其它的隊列(注意設置全局併發隊列無效)。
串行執行即統一在某個隊列執行
- (id)init {
self = [super init];
_protocolQueue = dispatch_queue_create("protocol.process.queue", NULL);
dispatch_queue_set_specific(_protocolQueue, _protocolQueueKey, (__bridge void *)self, NULL);
return self;
}
BOOL RCTIsMainQueue()
{
static void *mainQueueKey = &mainQueueKey;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_queue_set_specific(dispatch_get_main_queue(),
mainQueueKey, mainQueueKey, NULL);
});
return dispatch_get_specific(mainQueueKey) == mainQueueKey;
}
void runOnMainQueueWithoutDeadlocking(void (^block)(void)) {
if ([self RCTIsMainQueue]) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), block);
}
}
void runSynchronouslyOnProtocolProcessingQueue(void (^block)(void)) {
dispatch_queue_t processQueue = [[XXXConfig sharedInstance] protocolQueue];
if (dispatch_get_specific([[XXXConfig sharedInstance] protocolQueueKey])){
block();
} else {
dispatch_sync(processQueue, block);
}
}
防止死鎖
看看FMDB如何使用dispatch_queue_set_specific和dispatch_get_specific來防止死鎖的
static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;
//創建串行隊列,所有數據庫的操作都在這個隊列裏
_queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
//標記隊列
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
//檢查是否是同一個隊列來避免死鎖的方法
- (void)inDatabase:(void (^)(FMDatabase *db))block {
FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");
}