dispatch_barrier_async用法說明
dispatch_barrier_async用于等待前面的任務執(zhí)行完畢后自己才執(zhí)行,而它后面的任務需等待它完成之后才執(zhí)行。
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");
});
//等待前面的任務執(zhí)行完畢后自己才執(zhí)行,后面的任務需等待它完成之后才執(zhí)行
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
使用場景
一個典型的例子就是數(shù)據(jù)的讀寫,通常為了防止文件讀寫導致沖突,我們會創(chuàng)建一個串行的隊列,所有的文件操作都是通過這個隊列來執(zhí)行,比如FMDB,這樣就可以避免讀寫沖突。不過其實這樣效率是有提升的空間的,當沒有更新數(shù)據(jù)時,讀操作其實是可以并行進行的,而寫操作需要串行的執(zhí)行。