串联GCD知识点
-
dispatch_queue_t
// 声明一个queue
-
dispatch_queue_create(const char * label, dispatch_queque_attr_t attr)
// 创建一个串行(DISPATCH_QUEUE_SERIAL,一个队列,配上一个线程)或并发queue(DISPATCH_QUEUE_CONCURRENT, 一个队列,配上若干个线程)
- 异步执行:
dispatch_async(dispatch_queue_t queue, dispatch_block_t block)
同步执行:dispatch_sync(dispatch_queue_t queue, dispatch_block_t block)
// 使用
-
main dispatch queue
// 有且只有一个主队列,所有任务都在主线程中执行
-
dispatch_get_global_queue(long identifier, unsigned long flags)
// 使用GCD默认提供的全局并发队列, 第一个参数是优先级,第二个参数是做标记,供未来使用,大多数情况下应置为0
- 使用
serial queue
的特性保证资源的线程安全。相比lock unlock,更安全,性能更好,更清晰。
- GCD死锁相关
-
dispatch_semaphore_t
// 声明
-
dispatch_semaphore_create(long value)
// 创建
-
dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout)
// 等待信号量--(进入停车场)
-
dispatch_semaphore_signal(dispatch_semaphore_t dsema)
// 触发信号量++(离开停车场)
-
dispatch_semaphore_create(1)
// 相当于加锁
-
dispatch_semaphore_create(0)
// 用于在一个异步线程中控制先后顺序,事例如下:
-
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
NSLog(@"dispatch queue task");
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"wait for dispatch queue task completed");
-
dispatch_group_t
// 声明一个group
-
dispatch_group_create(void)
// 创建一个group
-
dispatch_group_async(group,queue,block)
// 给任务设置group
-
dispatch_group_wait(group, timeout)
//等待group里所有任务完成。示例代码:
self.upImageView.image = nil;
self.downImageView.image = nil;
__block UIImage *upImage = nil;
__block UIImage *downImage = nil;
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/h%3D300/sign=e1455acbde3f8794ccff4e2ee21b0ead/728da9773912b31bc351745a8c18367adab4e180.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
upImage = [UIImage imageWithData:data];
sleep(1);
});
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/h%3D300/sign=f7cc32133001213fd03348dc64e536f8/fc1f4134970a304e5fc3a630d8c8a786c8175c12.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
downImage = [UIImage imageWithData:data];
});
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
self.upImageView.image = upImage;
self.downImageView.image = downImage;
});