面试题如图,解决方案1:
@interface ViewController () {
int count;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
count = 0;
int n1 = arc4random()%10000;
int n2 = arc4random()%10000;
//要求func1循环n1次,func2循环n2次,并且必须并行运行,然后输出func3的结果
//如果只用下面这一个多线程方法,加分
// dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
// })
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue, ^{
for (int i = 0; i <n1; i ++) {
[self func1];
NSLog(@"func1");
}
});
dispatch_group_async(group, queue, ^{
for (int i = 0; i <n2; i ++) {
[self func2];
NSLog(@"func2");
}
});
for (int i = 0; i <n2; i ++) {
[self func1];
[self func2];
NSLog(@"func2");
}
dispatch_group_notify(group, queue, ^{
[self func3];
});
}
- (void)func1 {
count ++;
}
- (void)func2 {
count --;
}
- (void)func3 {
NSLog(@"%d",count);
}
如果只用一个异步操作的话,也有一种方法,用信号量机制,如下图: