函数介绍
一。dispatch_semaphore_create(M)
创建一个值为M的信号量
dispatch_semaphore_wait(信号量,等待时间)
如果该信号量的值大于0,则使其信号量的值-1,否则,阻塞线程直到该信号量的值大于0或者达到等待时间。
dispatch_semaphore_signal(信号量)
释放信号量,使得该信号量的值加1
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
for (int j = 0; j < 4; j ++) {
dispatch_group_async(group, queue, ^{
if (j == 0) {
[self loadOne:semaphore];
}else if (j == 1){
[self loadTwe:semaphore];
}else if (j == 2){
[self loadThree:semaphore];
}else{
[self loadFour:semaphore];
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
}
dispatch_group_notify(group, queue, ^{
//所有请求返回数据后执行
NSLog(@"完成");
});
- (void)loadOne:(dispatch_semaphore_t)group
{
//完成
dispatch_semaphore_signal(group);
}
二。使用GCD的dispatch_group_t
创建一个dispatch_group_t
每次网络请求前先dispatch_group_enter,请求回调后再dispatch_group_leave,enter和leave必须配合使用,有几次enter就要有几次leave,否则group会一直存在。
当所有enter的block都leave后,会执行dispatch_group_notify的block。
dispatch_group_t downloadGroup = dispatch_group_create();
NSString *requestURL11 = [NSString stringWithFormat:@"%@api/index/index?",MYURL];
dispatch_group_enter(downloadGroup);
[[HttpRequest sharedInstance] postWithURLString:requestURL11 headStr:nil parameters:nil success:^(id responseObject) {
NSLog(@"success11");
dispatch_group_leave(downloadGroup);
} failure:^(id failure) {
NSLog(@"failure111");
}];
NSString *requestURL22 = [NSString stringWithFormat:@"%@api/recommend/index?",MYURL];
dispatch_group_enter(downloadGroup);
[[HttpRequest sharedInstance] postWithURLString:requestURL22 headStr:nil parameters:nil success:^(id responseObject) {
NSLog(@"success22");
dispatch_group_leave(downloadGroup);
} failure:^(id failure) {
NSLog(@"failure22");
}];
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
NSLog(@"end");
});
三。