GCD(Grand Central Dispatch)俗称大中枢派发
- 线程改进示意图
- dispatch_queue_t 示意图
- 队列
dispatch_queue_t queue
- 创建队列
//第一个参数为队列名,第二个参数为串行或者并行
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
});
// 同步(必须执行完都something之后才会执行dispatch_sync之后的代码)
dispatch_sync(queue, ^{
// do something
});
-
dispatch queue 的种类
- Main Dispatch Queue
- 有且只有一个
- 里面所有的任务都是要在主线程中执行
-
Serial Queue
-
Concurrent Queue
- Main Dispatch Queue
一些内置的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 信号量,控制并发数
dispatch_group_t
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 把Queue中的任务统一放到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;
});
});
}