記錄我工作中使用到的GCD方法,定期更新完善。
Grand Central Dispatch (GCD) 是Apple開發的一個多核編程的較新的解決方法。
- GCD可用于多核的并行運算
- GCD會自動利用更多的CPU內核(比如雙核、四核)
- GCD會自動管理線程的生命周期(創建線程、調度任務、銷毀線程)
程序員只需要告訴GCD想要執行什么任務,不需要編寫任何線程管理代碼。但是看了很多文章,感覺GCD太大了,根本就記不住,所以寫下這個筆記,記錄下自己使用到的方法。
- 同時執行多個異步操作,都執行完畢,再執行某個方法。
// 創建信號量
_semaphore = dispatch_semaphore_create(0);
// 創建全局并行
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, ^{
// 請求一
//獲取輪播圖數據
[self getCarouselData];
});
dispatch_group_async(group, queue, ^{
// 請求二
//獲取首頁 3 和 8 張圖
[self getTemplateImg];
});
dispatch_group_notify(group, queue, ^{
// 2個請求對應2次信號等待
dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
//回到主線程刷新ui
dispatch_async(dispatch_get_main_queue(), ^{
DLog(@"------------ 請求完畢 ---------------");
[self.tableView reloadData];
[self.tableView.mj_header endRefreshing];
});
});
在請求方法獲取到數據時
//[self getCarouselData];
DLog(@"------------ 第一次 請求完畢 ---------------");
dispatch_semaphore_signal(_semaphore);
- GCD進行延遲操作
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:YES];
});
- GCD倒計時
__block int timeout= 59; //倒計時時間
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結束,關閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
[self.getCode setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
self.getCode.userInteractionEnabled = YES;
});
}else{
// int minutes = timeout / 60;
int seconds = timeout % 120;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
[self.getCode setTitle:[NSString stringWithFormat:@"%@秒后重獲",strTime] forState:UIControlStateNormal];
self.getCode.userInteractionEnabled = NO;
});
timeout--;
}
});
dispatch_resume(_timer);
4.異步操作,主線程刷新UI
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//通知主線程刷新
dispatch_async(dispatch_get_main_queue(), ^{
//回調或者說是通知主線程刷新,
[self.mTableView reloadData];;
});
});
5.調度組
//1.創建調度組
dispatch_group_t group = dispatch_group_create();
//2.隊列
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
//3.調度組監聽隊列
dispatch_group_enter(group);
dispatch_group_async(group, q, ^{
sleep(1);
NSLog(@"download 1");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_group_async(group, q, ^{
NSLog(@"download 2");
dispatch_group_leave(group);
});
dispatch_group_notify(group, q, ^{
NSLog(@"完成");
});