初识 GCD 中的 dispatch_barrier_asyn
2016-12-27 本文已影响0人
Seimda
void
dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);
提交一个异步执行的代码块到队列中执行
它有2个参数:queue为dispatch_barrier_async 作用的队列,block 为进入此队列执行的代码块
值得注意的是:dispatch_barrier_async 函数只有在 DISPATCH_QUEUE_CONCURRENT 队列中才起作用,在全局并发队列 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 中无效
dispatch_barrier_async 效果类似 dispatch_async,区别就是中间多了一个barrier,barrier顾名思义就是屏障的意思,将队列一分为2,前面的代码执行完才能执行dispatch_barrier_async中的任务,最后执行队列后的任务
例如
dispatch_queue_t concurrent_queue = dispatch_queue_create("concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-1--%@",[NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-2--%@",[NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-3--%@",[NSThread currentThread]);
});
dispatch_barrier_sync(concurrent_queue, ^(){
NSLog(@"dispatch_barrier_async--%@",[NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-4--%@",[NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-5--%@",[NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^(){
NSLog(@"task-6--%@",[NSThread currentThread]);
});
使用dispatch_barrier_async
2016-12-26 22:29:13.983 GCD[1443:100483] task-1--<NSThread: 0x7f8cc1d755d0>{number = 4, name = (null)}
2016-12-26 22:29:13.983 GCD[1443:100491] task-3--<NSThread: 0x7f8cc1e07960>{number = 3, name = (null)}
2016-12-26 22:29:13.983 GCD[1443:100472] task-2--<NSThread: 0x7f8cc1f01450>{number = 2, name = (null)}
2016-12-26 22:29:13.984 GCD[1443:100472] dispatch_barrier_async--<NSThread: 0x7f8cc1f01450>{number = 2, name = (null)}
2016-12-26 22:29:13.984 GCD[1443:100472] task-4--<NSThread: 0x7f8cc1f01450>{number = 2, name = (null)}
2016-12-26 22:29:13.984 GCD[1443:100483] task-6--<NSThread: 0x7f8cc1d755d0>{number = 4, name = (null)}
2016-12-26 22:29:13.984 GCD[1443:100491] task-5--<NSThread: 0x7f8cc1e07960>{number = 3, name = (null)}
使用dispatch_barrier_sync
2016-12-26 22:20:27.318 GCD[1420:95930] task-2--<NSThread: 0x7fad53d3faf0>{number = 3, name = (null)}
2016-12-26 22:20:27.318 GCD[1420:95919] task-1--<NSThread: 0x7fad53c1c360>{number = 2, name = (null)}
2016-12-26 22:20:27.318 GCD[1420:95936] task-3--<NSThread: 0x7fad53f01c90>{number = 4, name = (null)}
2016-12-26 22:20:27.319 GCD[1420:95836] dispatch_barrier_sync--<NSThread: 0x7fad53d07de0>{number = 1, name = main}
2016-12-26 22:20:27.320 GCD[1420:95936] task-4--<NSThread: 0x7fad53f01c90>{number = 4, name = (null)}
2016-12-26 22:20:27.320 GCD[1420:95930] task-6--<NSThread: 0x7fad53d3faf0>{number = 3, name = (null)}
2016-12-26 22:20:27.320 GCD[1420:95919] task-5--<NSThread: 0x7fad53c1c360>{number = 2, name = (null)}
task-1/2/3 和 task-4/5/6 分别并发执行,dispatch_barrier_async就像一座屏障,把1/2/3和4/5/6分隔开来,
dispatch_barrier_sync 与 dispatch_barrier_async 的区别则是同步和异步的区别,可以参照 dispatch_sync 和 dispatch_async