dispatch_group_t所使用的的方法
dispatch_group_create(); //创建一个线程组
dispatch_group_async(group, queue, ^{//将block任务添加到queue队列,并被group组管理
});
dispatch_group_enter(group); // 下面的任务交给线程组管理
dispatch_async(queue, ^{
sleep(1);
NSLog(@"6");
dispatch_group_leave(group); // 任务完成,线程组任务 -1
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // 等待线程组任务完成才会执行下面的代码,功能有点类似 dispatch_group_notify
NSLog(@"123");
dispatch_group_notify(group, queue, ^{ // 线程组任务全部执行完毕的通知
NSLog(@"5");
});
下面是一个例子
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
sleep(1);
NSLog(@"1");
});
dispatch_group_async(group, queue, ^{
sleep(1);
NSLog(@"2");
});
dispatch_group_async(group, queue, ^{
sleep(1);
NSLog(@"3");
});
dispatch_group_async(group, queue, ^{
sleep(1);
NSLog(@"4");
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
sleep(1);
NSLog(@"6");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
sleep(1);
NSLog(@"7");
dispatch_group_leave(group);
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"123");
dispatch_group_notify(group, queue, ^{
NSLog(@"5");
});
打印结果
image.png
网友评论