一.gcd信号量控制
/创建信号量/
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, ^{
网络请求1 ^{
dispatch_semaphore_signal(semaphore);
}
});
dispatch_group_async(group, queue, ^{
网络请求2 ^{
dispatch_semaphore_signal(semaphore);
}
});
dispatch_group_notify(group, queue, ^{
/两个请求对应两次信号等待/
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
网络请求3
});
提示:信号量控制虽然好用,但是在复杂的项目中,多处用到信号量就需要考虑到各个信号量之间的干扰,导致线程堵塞,程序莫名停止,不会崩溃也找不到原因。
二. 1.定义1个int a值。完成一个网络请求,a的值 +1,
2.用KVO监测a的值>=2,执行网络请求3
三. dispatch_group_t serviceGroup = dispatch_group_create();
// 网络请求1
dispatch_group_enter(serviceGroup);
[self.configService startWithCompletion:^(ConfigResponse *results, NSError* error){
// Do something with the results
configError = error;
dispatch_group_leave(serviceGroup);
}];
// 网络请求2
dispatch_group_enter(serviceGroup);
[self.preferenceService startWithCompletion:^(PreferenceResponse *results, NSError* error){
// Do something with the results
preferenceError = error;
dispatch_group_leave(serviceGroup);
}];
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
// Assess any errors
NSError *overallError = nil;
if (configError || preferenceError)
{
// Either make a new error or assign one of them to the overall error
overallError = configError ?: preferenceError;
}
// 网络请求3
completion(overallError);
});