- 一个接口的请求,依赖于另一个请求的结果
- 使用
GCD组队列中的dispatch_group_async和dispatch_group_notify
- (void)dispatchGroup{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"11111");
});
dispatch_group_notify(group, queue, ^{
NSLog(@"2222222");
});
}
- 使用
GCD的栅栏函数dispatch_barrier_async
- (void)dispatchBarrier{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"11111");
});
dispatch_barrier_async(queue, ^{
NSLog(@"22222");
});
}
- 使用
GCD的信号量dispatch_semaphore,信号量的初始值可以用来控制线程并发访问的最大数量。如果设置为1则为串行执行,达到线程同步的目的
- (void)dispatchSemaphore{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(queue, ^{
NSLog(@"11111");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
// 无限等待,直到请求1结束 增加了信号量,大于0后才开始,dispatch_semaphore_wait()信号减1
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"22222");
});
}
- 在异步线程中
return一个字符串
- 模拟异步线程方法,需要
return字符串@"小熊"
- (void)asyncRequestMethod:(void(^)(NSString *name))successBlock{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
if (successBlock) {
successBlock(@"小熊");
}
});
}
- (NSString *)nameStr{
__block NSString *nameStr = @"小关";
__block BOOL isSleep = YES;
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
NSLog(@"1");
isSleep = NO;
NSLog(@"3");
}];
while (isSleep) {
NSLog(@"4");
}
NSLog(@"2");
return nameStr;
}
- (NSString *)nameStr{
__block NSString *nameStr = @"小关"
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0)
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
dispatch_semaphore_signal(semaphore);
}]
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return nameStr
}
- 利用
dispatch_group_t调度组,异步改同步
- (NSString *)nameStr{
__block NSString *nameStr = @"小关"
dispatch_group_t group = dispatch_group_create()
dispatch_group_enter(group)
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
dispatch_group_leave(group);
}]
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
return nameStr
}
附:GrandCentralDispatchDemo