dispatch_barrier_async是在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行.
在如下场景:
在访问数据操作时,可以并行读取,因此这种操作应该放到concurrent Dispatch Queue中,写入操作是在任何读取操作执行之前,放到serial Dispatch Queue,在写入处理结束之前,读取处理操作不可进行。
此时使用dispatch_barrier_async和dispatch_group配合可以很好的解决这个问题。
示例:
[NSThread currentThread].name=@"mainThread";
dispatch_queue_t queue=dispatch_queue_create("RICHARD", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
[NSThread currentThread].name=@"blk0";
[NSThread sleepForTimeInterval:4];
NSLog(@"blk0");});
dispatch_async(queue, ^{
[NSThread currentThread].name=@"blk1";
[NSThread sleepForTimeInterval:2];
NSLog(@"blk1");});
dispatch_barrier_async(queue, ^{NSLog(@"dispatch_barrier");
[NSThread sleepForTimeInterval:5];
});
dispatch_async(queue, ^{
[NSThread currentThread].name=@"blk2";
[NSThread sleepForTimeInterval:3];
NSLog(@"blk2");});
NSLog(@"hello");
执行结果:
2015-01-31 12:22:36.956 testApp[1206:25015] hello
2015-01-31 12:22:38.957 testApp[1206:25076] blk1
2015-01-31 12:22:40.957 testApp[1206:25075] blk0
2015-01-31 12:22:40.957 testApp[1206:25075] dispatch_barrier
2015-01-31 12:22:48.960 testApp[1206:25075] blk2
原文地址:http://blog.csdn.net/richard_rufeng/article/details/43340059