平时运用总会遇到几个网络请求需要同时进行:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //创建信号量
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, ^{
NSLog(@"-->> 这是并发任务A");
for (int i = 0; i<100; i++) {
NSLog(@"正在处理A %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"-->> 这是并发任务B");
for (int i = 0; i<100; i++) {
NSLog(@"正在处理B %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"-->> 这是并发任务C");
for (int i = 0; i<100; i++) {
NSLog(@"正在处理C %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"-->> 这是并发任务D");
for (int i = 0; i<100; i++) {
NSLog(@"正在处理D %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_notify(group, queue, ^{ //四个请求对应四次信号等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"----->>>> 渲染UI");
});
网友评论