GCD中的兩個核心概念
- 任務
任務指的是放入GCD中的操作,一般以Block的方式進行,執行任務的操作有兩種
- 同步執行:不會開啟新的線程,在當前線程中執行,表現為同步函數sync
- 異步執行:擁有開啟新線程的執行任務的能力,表現為異步函數async
- 隊列
任務隊列是用來存放任務的隊列,采用先進先出的原則,隊列也分為兩種
- 串行隊列:隊列中的任務一個接一個的執行,不會開啟新的線程
- 并發隊列:在異步函數中會開啟多條線程,同時執行任務
創建隊列
- 創建串行隊列
// 創建串行隊列
dispatch_queue_t serialQueue = dispatch_queue_create("mySerialQueue", DISPATCH_QUEUE_SERIAL);
- 主隊列也為一個特殊的串行隊列,不需要創建,可以直接獲取
// 獲取主隊列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
- 創建并發隊列
// 創建并發隊列
dispatch_queue_t concurrentQueue = dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
- 全局并發隊列也不需要創建,可以直接獲取
// 獲取全局并發隊列
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
創建任務
- 創建同步執行的任務
// 同步函數+串行隊列
dispatch_sync(serialQueue, ^{
// 不會開啟新的線程
NSLog(@"%@",[NSThread currentThread]);
});
// 同步函數+主隊列
dispatch_sync(mainQueue, ^{
// 不會開啟新的線程
NSLog(@"%@",[NSThread currentThread]);
});
// 同步函數+并發隊列
dispatch_sync(concurrentQueue, ^{
// 不會開啟新的線程
NSLog(@"%@",[NSThread currentThread]);
});
- 創建異步執行的任務
// 異步函數+并發隊列
dispatch_async(concurrentQueue, ^{
// 開啟新的線程
NSLog(@"%@",[NSThread currentThread]);
});
// 異步函數+串行隊列
dispatch_async(serialQueue, ^{
// 開啟一條后臺線程,串行執行任務
NSLog(@"%@",[NSThread currentThread]);
});
// 異步函數+主隊列
dispatch_async(mainQueue, ^{
// 不開起新的線程
NSLog(@"%@",[NSThread currentThread]);
});
代碼驗證
- 串行隊列+同步函數
#pragma mark - 串行隊列+同步函數
- (void)configSyncSerialQueue {
NSLog(@"開始執行");
NSArray *titleArray = @[@"第一個任務",@"第二個任務",@"第三個任務"];
dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue""", DISPATCH_QUEUE_SERIAL);
for (NSString *str in titleArray) {
dispatch_sync(serialQueue, ^{
NSLog(@"串行隊列+同步函數:%@--%@",str,[NSThread currentThread]);
});
}
for (NSString *str in titleArray) {
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"主隊列+同步函數:%@--%@",str,[NSThread currentThread]);
});
}
}
Snip20180118_4.png
沒有開啟新的線程,均在主線程中執行
- 串行隊列+異步函數
#pragma mark - 串行隊列+異步函數
- (void)configAsyncSerialQueue {
NSLog(@"開始執行");
NSArray *titleArray = @[@"第一個任務",@"第二個任務",@"第三個任務"];
dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue""", DISPATCH_QUEUE_SERIAL);
for (NSString *str in titleArray) {
dispatch_async(serialQueue, ^{
NSLog(@"串行隊列+異步函數:%@--%@",str,[NSThread currentThread]);
});
}
for (NSString *str in titleArray) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"主隊列+異步函數:%@--%@",str,[NSThread currentThread]);
});
}
}
Snip20180118_5.png
可以發現,串行隊列+異步函數的組合開啟了新的線程,而主隊列+異步函數確沒有開啟新的線程,任在主線程執行任務.
#pragma mark - 并發隊列+同步函數
- (void)configSyncConcurrentQueue {
NSLog(@"開始執行");
NSArray *titleArray = @[@"第一個任務",@"第二個任務",@"第三個任務"];
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentQueue""", DISPATCH_QUEUE_CONCURRENT);
for (NSString *str in titleArray) {
dispatch_sync(concurrentQueue, ^{
NSLog(@"并發隊列+同步函數:%@--%@",str,[NSThread currentThread]);
});
}
for (NSString *str in titleArray) {
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
NSLog(@"全局并發隊列+同步函數:%@--%@",str,[NSThread currentThread]);
});
}
}
Snip20180118_6.png
可見,同步函數不具有開啟新線程的能力
#pragma mark - 并發隊列+異步函數
- (void)configAsyncConcurrentQueue {
NSLog(@"開始執行");
NSArray *titleArray = @[@"第一個任務",@"第二個任務",@"第三個任務"];
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentQueue""", DISPATCH_QUEUE_CONCURRENT);
for (NSString *str in titleArray) {
dispatch_async(concurrentQueue, ^{
NSLog(@"并發隊列+異步函數:%@--%@",str,[NSThread currentThread]);
});
}
for (NSString *str in titleArray) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"全局并發隊列+異步函數:%@--%@",str,[NSThread currentThread]);
});
}
}
Snip20180118_7.png
開啟了新的線程,任務并發執行
注意:在使用過程中需要注意死鎖問題!
所謂死鎖,通常指有兩個線程A和B都卡住了,A在等B ,B在等A,相互等待對方完成某些操作。A不能完成是因為它在等待B完成。但B也不能完成,因為它在等待A完成。于是大家都完不成,就導致了死鎖
#pragma mark - 死鎖案例
- (void)deadLock {
NSLog(@"任務1");
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"任務2");
});
NSLog(@"任務3");
}
- 任務1,2,3都加入到了主隊列中
- 同步函數+主隊列不會開啟新的線程
- 所有任務都在主線程執行
首先執行任務1,接下來,程序遇到了同步線程,那么它會進入等待,等待任務2執行完,然后執行任務3.但這是主隊列,是一個特殊的串行隊列,有任務來,會將任務加到隊尾,然后遵循FIFO原則執行任務.那么,現在任務2就會被加到最后,任務3排在了任務2前面.但是任務3要等任務2執行完才能執行,任務2又排在任務3后面,意味著任務2要在任務3執行完才能執行,所以他們進入了互相等待的局面,程序就卡在了這里,這就是死鎖.
GCD的具體應用
- 線程間通信
在iOS開發中,主線程有稱為UI線程,用來處理UI事件.其他耗時操作通常放在子線程中進行,比如網絡請求等.通過網絡請求回來的數據通常需要用UI展示,這是就需要從子線程回到主線程,進而就產生了線程間通信.
#pragma mark - 線程間通信
- (void)GCDCommunication {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 全局并發隊列中異步請求數據
NSArray *dataArray = @[@"我是第1條數據",@"我是第2條數據",@"我是第3條數據"];
for (NSString *dataStr in dataArray) {
NSLog(@"%@---我當前的線程是:%@",dataStr,[NSThread currentThread]);
}
// 請求數據完成,回到主線程刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"我當前的線程是:%@",[NSThread currentThread]);
});
});
}
Snip20180118_8.png
可以看到,在子線程中請求完數據之后又回到了主線程中執行任務
- GCD定時器
首先NSTimer可以做定時器,但是它受到RunLoop的Mode影響,不是特別準確,而且容易造成循環引用的問題.GCD定時器可以規避這些問題.
int count = 0;
- (void)GCDTimer {
self.gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC); // 從現在開始兩秒后執行
dispatch_source_set_timer(self.gcdTimer, startTime, (int64_t)(2.0 * NSEC_PER_SEC), 0); // 每兩秒執行一次
// 定時器回調
dispatch_source_set_event_handler(self.gcdTimer, ^{
NSLog(@"CGD定時器-----%@",[NSThread currentThread]);
count++;
if (count == 5) { // 執行5次,讓定時器取消
dispatch_cancel(self.gcdTimer);
self.gcdTimer = nil;
}
});
// 啟動定時器: GCD定時器默認是暫停的
dispatch_resume(self.gcdTimer);
}
- GCD控制并發
GCD中控制并發可以通過
dispatch_group 隊列組
dispatch_barrier 柵欄函數
dispatch_semahpore 信號量
來控制
1.dispatch_group
在某些特殊的場景下我們需要同時執行多個耗時任務,并且在多個任務都完成的之后在回到主線程刷新UI,此時就可以使用dispath_group了
#pragma mark - configDispatch_group
- (void)configDispatch_group {
dispatch_group_t gcdGroup = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(gcdGroup, queue, ^{
NSLog(@"執行第一個任務");
});
dispatch_group_async(gcdGroup, queue, ^{
NSLog(@"執行第二個任務");
});
dispatch_group_async(gcdGroup, queue, ^{
NSLog(@"執行第三個任務");
});
dispatch_group_notify(gcdGroup, dispatch_get_main_queue(), ^{
NSLog(@"回到了主線程");
});
}
Snip20180118_9.png
在執行完了任務1,2,3之后回到了主線程,起到了控制的作用
- dispatch_barrier 柵欄函數
當一個任務的執行與否依賴于上一個任務執行的結果的時候我們可以使用dispatch_barrier,柵欄函數的作用在于控制并發任務執行的先后順序
#pragma mark - dispatch_barrier
- (void)configDispatch_barrier {
// dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"執行第一個任務--%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"執行第二個任務--%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"執行第三個任務--%@",[NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"我是柵欄,前邊的任務都執行完了,在執行下邊的任務--%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"執行第四個任務--%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"執行第五個任務--%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"執行第六個任務--%@",[NSThread currentThread]);
});
}
Snip20180118_10.png
注意:這里的dispatch_queue_t queue中的queue必須為dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)創建的,使用全局并發隊列不起作用
- dispatch_semahpore 信號量
有時候在開發中我們希望執行完一個任務(成功/失敗)才接著執行下一個任務,這是我們可以使用信號量來控制
信號量運行準則:
信號量就是一個資源計數器,當其不為0時線程正常運行,為0時則阻塞當前線程.
實現原理:
使用信號量的PV操作來實現互斥.P:信號量-1,V:信號量+1
例如:
默認初始信號量為1
當A正常運行,使用資源;對信號量實施P操作,信號量-1
當B期望使用資源來正常運行,發現信號量為0(阻塞),B一直等待
A執行完成,進行V操作,釋放資源,信號量+1
B檢測到信號量不為0,則正常運行
#pragma mark - 信號量
- (void)configDispatch_semaphore {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// 創建信號量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
NSArray *titleArray = @[@(1),@(1),@(1),@(0),@(1)];
for (int i = 0; i<titleArray.count; i++) {
int number = [titleArray[i] intValue];
dispatch_async(queue, ^{
//信號量為0是則阻塞當前線程,不為0則減1繼續執行當前線程
dispatch_wait(semaphore, DISPATCH_TIME_FOREVER);
if (number) {
NSLog(@"%d--當前線程:%@",i,[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
} else {
NSLog(@"%d--當前線程:%@",i,[NSThread currentThread]);
dispatch_semaphore_signal(semaphore);
}
});
}
}
Snip20180118_11.png
可見,信號量起到了控制任務執行順序的作用
- GCD延時函數
#pragma mark - GCD延時函數
- (void)configDispatch_after {
NSLog(@"開始執行");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"兩秒后我執行了");
});
}
- GCD一次性代碼
通常用于創建單列
#pragma mark - GCD一次性代碼
- (void)configDispatch_once {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 這里寫只需要執行一次的代碼,默認線程安全
});
}
- GCD快速迭代(遍歷)
GCD快速遍歷與for,while循環不同,它會開啟新的線程來遍歷(在并發隊列中)
- (void)configDispatch_apply {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_apply(15, queue, ^(size_t index) {
NSLog(@"執行第%ld個任務,當前線程為%@",index,[NSThread currentThread]);
});
}
Snip20180118_12.png
可以看出,GCD快速迭代是在不同線程中執行的,而且還包含了主線程.
注意,這里的快速迭代是在并發隊列中執行的,如果放在串行隊列中,操作會在主線程中執行,沒有起到快速迭代的作用
- (void)configDispatch_apply {
// dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_queue_t queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_apply(15, queue, ^(size_t index) {
NSLog(@"執行第%ld個任務,當前線程為%@",index,[NSThread currentThread]);
});
}
Snip20180118_13.png
同時應該注意,這里不要使用主隊列,在快速迭代使用的線程中包括了主線程,會造成死鎖現象
以上內容就是我在iOS開發過程中所理解和使用到的GCD相關內容,如有嚴謹的地方請讀者糾正,謝謝!
以上代碼demo地址:https://github.com/geekGetup/GCD