定义了两个变量和三个函数 要求func1循环n1次 func2循环n2次 之后调用func3.
如果能在一个异步函数中实现,额外加分
int n1 = arc4random() % 1000;
int n2 = arc4random() % 1000;
- (void)func1 {
self.count++;
}
- (void)func2 {
self.count--;
}
- (void)func3 {
NSLog(@"a%d %d", __LINE__ ,self.count);
}
因为好久没碰iOS了,及其生疏 居然脑袋里一片空白 这明摆着dispatch_group啊
害,gcd组太好实现了,就不说了 看下怎么在一个异步函数中实现吧
其实用到了信号量 ,用信号量来拦截前两个异步任务 信号量恢复0后再去执行func3,重点其实在于第三个函数前的两个wait函数 一定要wait两次,才能拦截两个异步任务。
大胆猜测一下,系统的gcd组应该用的也是信号量吧 哈哈哈
dispatch_semaphore_t seam = dispatch_semaphore_create(2);
dispatch_queue_t queue = dispatch_queue_create("lion", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_semaphore_wait(seam, DISPATCH_TIME_FOREVER);
dispatch_async(queue, ^{
for (int i =0; i<n1; i++) {
[self func1];
NSLog(@"n1: %d", i);
}
dispatch_semaphore_signal(seam);
});
dispatch_semaphore_wait(seam, DISPATCH_TIME_FOREVER);
dispatch_async(queue, ^{
for (int i = 0; i < n2; i++) {
[self func2];
NSLog(@"n2: %d", i);
}
dispatch_semaphore_signal(seam);
});
dispatch_semaphore_wait(seam, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(seam, DISPATCH_TIME_FOREVER);
[self func3];
dispatch_semaphore_signal(seam);
dispatch_semaphore_signal(seam);
});