1、GCD实现
- (int)syncGetCountWithDispatchGroup
{
// _block 修饰才能在block块里面更改值
__block int count = 0;
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
// 异步方法
[self AsyncGetCount:^(NSInteger value) {
count = value;
dispatch_group_leave(group);
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
// 利用线程组阻塞、必须调用异步取值才能走下一步
return count;
}
- (void)moreNetLoadWithDispatchGroup
{
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
// 异步网络方法1
[self AsyncLoadrequest1:^(NetModel *value) {
dispatch_group_leave(group);
}];
// 异步网络方法2
dispatch_group_enter(group);
[self AsyncLoadrequest2:^(NetModel *value) {
dispatch_group_leave(group);
}];
// 必须两个任务走完才能走下一步
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 最后的操作
});
}
2、信号量实现
- (int)syncGetCountWithSemaphore
{
__block int count = 0;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[self AsyncGetCount:^(NSInteger value) {
count = value;
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return result;
}
网友评论