作用
- 實(shí)現(xiàn)高效率的數(shù)據(jù)庫訪問和文件訪問
- 避免數(shù)據(jù)競爭
前提條件
- 必須使用
dispatch_queue_create
創(chuàng)建隊(duì)列 - 且隊(duì)列屬性為
DISPATCH_QUEUE_CONCURRENT
(注意:使用dispatch_barrier_async
讼呢,該函數(shù)只能搭配自定義并行隊(duì)列dispatch_queue_t
使用往衷。不能使用:dispatch_get_global_queue
,否則dispatch_barrier_async
的作用會(huì)和dispatch_async
的作用一模一樣联予。 )
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"--1---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"--2---%@",[NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"--barrier---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"--3---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"--4---%@",[NSThread currentThread]);
});
結(jié)果
2017-06-30 17:34:11.889 test[50672:716568] --1---<NSThread: 0x6080000792c0>{number = 3, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --2---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --barrier---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --3---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716568] --4---<NSThread: 0x6080000792c0>{number = 3, name = (null)}
其中 --barrier---
前的和后的是不確定的,但3,4 一定在1葵腹,2 后面執(zhí)行
參考鏈接