我们在开发的过程中,可能碰到如下的情况:异步下载两张图片,然后合并成一张图片。此时就需要使用dispatch group,如下面代码所示:
- (void)group {
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("QuequName", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{
for (int i=0; i<10; i++) {
NSLog(@"---%d", i);
}
});
dispatch_group_async(group, queue, ^{
for (int i=0; i<10; i++) {
NSLog(@"===%d", i);
}
});
NSLog(@"hello");
dispatch_group_notify(group, queue, ^{
NSLog(@"End of line");
});
NSLog(@"world");
}
控制台输出结果:
2018-04-19 14:08:32.980061+0800 Barrier[69501:2678923] ---0
2018-04-19 14:08:32.980060+0800 Barrier[69501:2678875] hello
2018-04-19 14:08:32.980060+0800 Barrier[69501:2678925] ===0
2018-04-19 14:08:32.980210+0800 Barrier[69501:2678923] ---1
2018-04-19 14:08:32.980214+0800 Barrier[69501:2678925] ===1
2018-04-19 14:08:32.980214+0800 Barrier[69501:2678875] world
2018-04-19 14:08:32.980298+0800 Barrier[69501:2678923] ---2
2018-04-19 14:08:32.980355+0800 Barrier[69501:2678925] ===2
2018-04-19 14:08:32.980432+0800 Barrier[69501:2678923] ---3
2018-04-19 14:08:32.980717+0800 Barrier[69501:2678925] ===3
2018-04-19 14:08:32.980912+0800 Barrier[69501:2678923] ---4
2018-04-19 14:08:32.981162+0800 Barrier[69501:2678925] ===4
2018-04-19 14:08:32.981587+0800 Barrier[69501:2678923] ---5
2018-04-19 14:08:32.982290+0800 Barrier[69501:2678925] ===5
2018-04-19 14:08:32.982526+0800 Barrier[69501:2678923] ---6
2018-04-19 14:08:32.982867+0800 Barrier[69501:2678925] ===6
2018-04-19 14:08:32.983203+0800 Barrier[69501:2678923] ---7
2018-04-19 14:08:32.983589+0800 Barrier[69501:2678925] ===7
2018-04-19 14:08:32.983999+0800 Barrier[69501:2678923] ---8
2018-04-19 14:08:32.984437+0800 Barrier[69501:2678925] ===8
2018-04-19 14:08:32.984847+0800 Barrier[69501:2678923] ---9
2018-04-19 14:08:32.986048+0800 Barrier[69501:2678925] ===9
2018-04-19 14:08:32.986504+0800 Barrier[69501:2678925] Barrier:0
2018-04-19 14:08:32.986978+0800 Barrier[69501:2678925] Barrier:1
2018-04-19 14:08:32.987478+0800 Barrier[69501:2678925] Barrier:2
2018-04-19 14:08:32.987857+0800 Barrier[69501:2678925] Barrier:3
2018-04-19 14:08:32.988693+0800 Barrier[69501:2678925] Barrier:4
2018-04-19 14:08:32.989132+0800 Barrier[69501:2678925] End of line