GCD中的dispatch_barrier_async函数的使用
2018-04-19 本文已影响52人
George2016
一、什么是dispatch_barrier_async
函数
毫无疑问,dispatch_barrier_async函数的作用与barrier的意思相同,在进程管理中起到一个栅栏的作用,它等待所有位于barrier函数之前的操作执行完毕后执行,并且在barrier函数执行之后,barrier函数之后的操作才会得到执行,该函数需要同dispatch_queue_create函数生成的concurrent Dispatch Queue队列一起使用
二、dispatch_barrier_async
函数的作用
1.实现高效率的数据库访问和文件访问
2.避免数据竞争
三、什么情况下要用到dispatch_barrier_async
函数
发送10个网络请求,然后再接收到所有回应之后执行后续操作,如何实现?
四、dispatch_barrier_async
实例
- (void)barrier {
dispatch_queue_t queue = dispatch_queue_create("QueueName", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
for (int i=0; i<10; i++) {
NSLog(@"---%d", i);
}
});
dispatch_async(queue, ^{
for (int i=0; i<10; i++) {
NSLog(@"===%d", i);
}
});
dispatch_barrier_async(queue, ^{
for (int i=0; i<5; i++) {
NSLog(@"Barrier:%d", i);
}
});
dispatch_async(queue, ^{
NSLog(@"End of line");
});
}
输出:
2018-04-19 13:43:59.289120+0800 Barrier[68777:2612453] ---0
2018-04-19 13:43:59.289120+0800 Barrier[68777:2612452] ===0
2018-04-19 13:43:59.289312+0800 Barrier[68777:2612452] ===1
2018-04-19 13:43:59.289312+0800 Barrier[68777:2612453] ---1
2018-04-19 13:43:59.289412+0800 Barrier[68777:2612452] ===2
2018-04-19 13:43:59.289435+0800 Barrier[68777:2612453] ---2
2018-04-19 13:43:59.289517+0800 Barrier[68777:2612452] ===3
2018-04-19 13:43:59.289571+0800 Barrier[68777:2612453] ---3
2018-04-19 13:43:59.289623+0800 Barrier[68777:2612452] ===4
2018-04-19 13:43:59.289723+0800 Barrier[68777:2612453] ---4
2018-04-19 13:43:59.289753+0800 Barrier[68777:2612452] ===5
2018-04-19 13:43:59.290924+0800 Barrier[68777:2612453] ---5
2018-04-19 13:43:59.291296+0800 Barrier[68777:2612452] ===6
2018-04-19 13:43:59.291651+0800 Barrier[68777:2612453] ---6
2018-04-19 13:43:59.292960+0800 Barrier[68777:2612452] ===7
2018-04-19 13:43:59.293533+0800 Barrier[68777:2612453] ---7
2018-04-19 13:43:59.295059+0800 Barrier[68777:2612452] ===8
2018-04-19 13:43:59.295317+0800 Barrier[68777:2612452] ===9
2018-04-19 13:43:59.295311+0800 Barrier[68777:2612453] ---8
2018-04-19 13:43:59.295531+0800 Barrier[68777:2612453] ---9
2018-04-19 13:43:59.296414+0800 Barrier[68777:2612453] Barrier:0
2018-04-19 13:43:59.298519+0800 Barrier[68777:2612453] Barrier:1
2018-04-19 13:43:59.298687+0800 Barrier[68777:2612453] Barrier:2
2018-04-19 13:43:59.298791+0800 Barrier[68777:2612453] Barrier:3
2018-04-19 13:43:59.299849+0800 Barrier[68777:2612453] Barrier:4
2018-04-19 13:43:59.300067+0800 Barrier[68777:2612453] End of line