先看下下面这段代码
__block int count = 0;
dispatch_queue_t queue = dispatch_queue_create("aaaaaaa", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"2 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"3 ------- %d",count);
});
dispatch_async(queue, ^{
count = 1; //write
NSLog(@"4 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"5 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"6 ------- %d",count);
});
//运行结果
(第三次运行)
2017-07-15 16:18:53.372 Test115[1998:65456] 2 ------- 0
2017-07-15 16:18:53.372 Test115[1998:65460] 3 ------- 0
2017-07-15 16:18:53.373 Test115[1998:65487] 4 ------- 1
2017-07-15 16:18:53.373 Test115[1998:65488] 5 ------- 1
2017-07-15 16:18:53.373 Test115[1998:65457] 1 ------- 1
2017-07-15 16:18:53.373 Test115[1998:65489] 6 ------- 1
(第五次运行)
2017-07-15 16:16:35.587 Test115[1905:62973] 4 ------- 1
2017-07-15 16:16:35.587 Test115[1905:62979] 3 ------- 0
2017-07-15 16:16:35.588 Test115[1905:62976] 2 ------- 1
2017-07-15 16:16:35.587 Test115[1905:62974] 1 ------- 0
2017-07-15 16:16:35.588 Test115[1905:62973] 6 ------- 1
2017-07-15 16:16:35.588 Test115[1905:62981] 5 ------- 1
根据CONCURRENT DISPATCH QUEUE的性质,有可能在追加到写入处理前面的处理中读取到与期待不符的数据(数据竞争)
因此要使用dispatch_barrier_async函数,dispatch_barrier_async函数会等待追加到Concurrent Dispatch Queue上的并行执行的处理全部结束之后,再将指定的处理追加到该Concurrent Dispatch Queue中。然后在由dispatch_barrier_async函数追加的处理执行完毕后,Concurrent Dispatch Queue才恢复为一般的动作,追加到该Concurrent Dispatch Queue的处理又开始并行执行。
__block int count = 0;
dispatch_queue_t queue = dispatch_queue_create("aaaaaaa", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"2 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"3 ------- %d",count);
});
dispatch_barrier_async(queue, ^{
count = 1; //write
NSLog(@"4 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"5 ------- %d",count);
});
dispatch_async(queue, ^{
NSLog(@"6 ------- %d",count);
});
打印结果
2017-07-15 16:38:09.585 Test115[2430:80763] 3 ------- 0
2017-07-15 16:38:09.585 Test115[2430:80761] 1 ------- 0
2017-07-15 16:38:09.585 Test115[2430:80781] 2 ------- 0
2017-07-15 16:38:09.585 Test115[2430:80781] 4 ------- 1
2017-07-15 16:38:09.586 Test115[2430:80761] 6 ------- 1
2017-07-15 16:38:09.586 Test115[2430:80781] 5 ------- 1
使用Concurrent Dispatch Queue 和 dispatch_barrier_async可实现高效率的数据库访问和文件访问