作用
- 實現高效率的數據庫訪問和文件訪問
- 避免數據競爭
前提條件
- 必須使用
dispatch_queue_create
創建隊列 - 且隊列屬性為
DISPATCH_QUEUE_CONCURRENT
(注意:使用dispatch_barrier_async
,該函數只能搭配自定義并行隊列dispatch_queue_t
使用。不能使用:dispatch_get_global_queue
,否則dispatch_barrier_async
的作用會和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]);
});
結果
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 后面執行
參考鏈接