dispatch_barrier_async用法说明
dispatch_barrier_async用于等待前面的任务执行完毕后自己才执行,而它后面的任务需等待它完成之后才执行。
dispatch_queue_t queue = dispatch_queue_create("gcdtest.rongfzh.yc", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"dispatch_async1");
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"dispatch_async2");
});
//等待前面的任务执行完毕后自己才执行,后面的任务需等待它完成之后才执行
dispatch_barrier_async(queue, ^{
NSLog(@"dispatch_barrier_async");
[NSThread sleepForTimeInterval:4];
NSLog(@"四秒后:dispatch_barrier_async");
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"dispatch_async3");
});
dispatch_async(queue, ^{
NSLog(@"dispatch_async4");
});
打印结果:
2017-05-05 10:31:49.563 Practice_Animation[5086:491804] dispatch_async2
2017-05-05 10:31:50.563 Practice_Animation[5086:491769] dispatch_async1
2017-05-05 10:31:50.563 Practice_Animation[5086:491769] dispatch_barrier_async
2017-05-05 10:31:54.566 Practice_Animation[5086:491769] 四秒后:dispatch_barrier_async
2017-05-05 10:31:54.566 Practice_Animation[5086:491804] dispatch_async4
2017-05-05 10:31:55.570 Practice_Animation[5086:491769] dispatch_async3
使用场景
一个典型的例子就是数据的读写,通常为了防止文件读写导致冲突,我们会创建一个串行的队列,所有的文件操作都是通过这个队列来执行,比如FMDB,这样就可以避免读写冲突。不过其实这样效率是有提升的空间的,当没有更新数据时,读操作其实是可以并行进行的,而写操作需要串行的执行。
网友评论