GCD(Grand Central Dispatch)俗稱大中樞派發(fā)
- 線程改進示意圖
- dispatch_queue_t 示意圖
- 隊列
dispatch_queue_t queue
- 創(chuàng)建隊列
//第一個參數(shù)為隊列名,第二個參數(shù)為串行或者并行
dispatch_queue_t queue = dispatch_queue_create("com.huangbaoqin.GCDQueue", DISPATCH_QUEUE_CONCURRENT);
- 使用隊列
dispatch_queue_t queue = dispatch_queue_create("com.huangbaoqin.GCDQueue", DISPATCH_QUEUE_CONCURRENT);
// 異步
dispatch_async(queue, ^{
// do something
});
// 同步(必須執(zhí)行完都something之后才會執(zhí)行dispatch_sync之后的代碼)
dispatch_sync(queue, ^{
// do something
});
-
dispatch queue 的種類
- Main Dispatch Queue
- 有且只有一個
- 里面所有的任務(wù)都是要在主線程中執(zhí)行
-
Serial Queue
-
Concurrent Queue
- Main Dispatch Queue
一些內(nèi)置的Queue
// #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
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
- dispatch_affter
// 不能取消
void
dispatch_after(dispatch_time_t when,
dispatch_queue_t queue,
dispatch_block_t block);
- GCD中的線程安全
dispatch_async(_queue, ^{
self.a ++;
})
死鎖
dispatch_once
+ (instancetype)sharedObj {
static singleOBJ *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[singleOBJ alloc] init];
});
return instance;
}
dispatch_semaphore_t 信號量惑折,控制并發(fā)數(shù)
dispatch_group_t
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 把Queue中的任務(wù)統(tǒng)一放到group中處理授账,在后臺線程中等待group處理完成后切換到主線程操作UI
_imageView1.image = nil;
_imageView2.image = nil;
_imageView3.image = nil;
_imageView4.image = nil;
__block UIImage *image1, *image2, *image3, *image4 = nil;
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url1]]];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
image2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url2]]];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
image3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url3]]];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
image4 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url4]]];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
_imageView1.image = image1;
_imageView2.image = image2;
_imageView3.image = image3;
_imageView4.image = image4;
});
});
}