需求
在开发中很多时候会有这样的场景,同一个界面有多个请求,而且要在这几个请求都成功返回的时候再去进行下一操作,对于这种场景,如何来设计请求操作呢?今天我们就来讨论一下有哪几种方案。
讨论
首先,我们需要先排除,一个请求结束之后再去请求另一个这种串行耗时的方法,我们所讨论的都是基于异步的基础上。我们先来看一个网络请求的代码:
//模拟一个网络请求方法 get/post/put...etc
- (void)httpRequest:(NSString *)method param:(NSDictionary *)param completion:(void(^)(id response))block{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *commend = [param objectForKey:commandKey];
NSLog(@"request:%@ run in thread:%@", commend, [NSThread currentThread]);
NSTimeInterval sleepInterval = arc4random() % 10;
[NSThread sleepForTimeInterval:sleepInterval];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"requset:%@ done!", commend);
block(nil);
});
});
}
方案一:使用Group
这种场景下,我们最容易想到的就是使用GCD的group来解决,但是情况真的如此吗?先来看看代码:
- (void)testUsingGCDGroup1{
NSArray *commandArray = @[@"requestcommand1", @"requestcommand2", @"requestcommand3", @"requestcommand4", @"requestcommand5"];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[commandArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
dispatch_group_async(group, queue, ^{
NSLog(@"%@ in group thread:%@", obj, [NSThread currentThread]);
[self httpRequest:nil param:@{commandKey : obj} completion:^(id response) {
}];
});
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"all http request done!");
NSLog(@"UI update in main thread!");
});
}
我们来看一下运行结果:
2017-07-20 11:33:27.336 TestMutiRequest[1345:82575] requestcommand2 in group thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-07-20 11:33:27.336 TestMutiRequest[1345:82576] requestcommand1 in group thread:<NSThread: 0x60000007f2c0>{number = 3, name = (null)}
2017-07-20 11:33:27.336 TestMutiRequest[1345:82578] requestcommand3 in group thread:<NSThread: 0x608000263c00>{number = 5, name = (null)}
2017-07-20 11:33:27.336 TestMutiRequest[1345:82638] requestcommand4 in group thread:<NSThread: 0x600000262b00>{number = 6, name = (null)}
2017-07-20 11:33:27.336 TestMutiRequest[1345:82575] requestcommand5 in group thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-07-20 11:33:27.336 TestMutiRequest[1345:82576] request:requestcommand2 run in thread:<NSThread: 0x60000007f2c0>{number = 3, name = (null)}
2017-07-20 11:33:27.337 TestMutiRequest[1345:82639] request:requestcommand1 run in thread:<NSThread: 0x608000264000>{number = 7, name = (null)}
2017-07-20 11:33:27.337 TestMutiRequest[1345:82578] request:requestcommand3 run in thread:<NSThread: 0x608000263c00>{number = 5, name = (null)}
2017-07-20 11:33:27.337 TestMutiRequest[1345:82638] request:requestcommand4 run in thread:<NSThread: 0x600000262b00>{number = 6, name = (null)}
2017-07-20 11:33:27.338 TestMutiRequest[1345:82575] request:requestcommand5 run in thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-07-20 11:33:27.391 TestMutiRequest[1345:82507] all http request done!
2017-07-20 11:33:27.429 TestMutiRequest[1345:82507] UI update in main thread!
2017-07-20 11:33:27.432 TestMutiRequest[1345:82507] requset:requestcommand2 done!
2017-07-20 11:33:27.435 TestMutiRequest[1345:82507] requset:requestcommand3 done!
2017-07-20 11:33:27.437 TestMutiRequest[1345:82507] requset:requestcommand4 done!
2017-07-20 11:33:28.347 TestMutiRequest[1345:82507] requset:requestcommand5 done!
2017-07-20 11:33:35.399 TestMutiRequest[1345:82507] requset:requestcommand1 done!
结果显而易见了,并不是我们想要的那种结果,在这里group的作用只是把你的各个请求都分发出去了,确实是都调了各个请求,但是请求是异步的,调了请求并不代表已经返回结果了,也就是说,group并没有等待异步的请求成功之后才去调用notify,而是调了请求之后就去调用notify,导致请求成功调用在notify之后。可以这么总结一下:
这里的任务是有要求的,这里的任务必须要是同步执行的!!如果任务是异步的,group只会执行完任务里面异步之前的代码以及分发异步任务就返回了!!也就代表分发group的当前这个任务完成了!但事实却是这个任务的一部分子任务在其他线程执行了,而且不一定已执行结束返回。
所以现在的解决办法就是把分发到group的任务变成同步执行。
方案二:使用改进之后的Group(使用dispatch_semaphore_t使单个请求任务同步执行。)
- (void)httpRequest2:(NSString *)method param:(NSDictionary *)param completion:(void(^)(id response))block{
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self httpRequest:method param:param completion:^(id response) {
if (block) {
block(response);
}
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
testUsingGCDGroup方法也相应改成对httpRequest2方法的调用
- (void)testUsingGCDGroup2{
NSArray *commandArray = @[@"requestcommand1", @"requestcommand2", @"requestcommand3", @"requestcommand4", @"requestcommand5"];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[commandArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
dispatch_group_async(group, queue, ^{
NSLog(@"%@ in group thread:%@", obj, [NSThread currentThread]);
[self httpRequest2:nil param:@{commandKey : obj} completion:^(id response) {
}];
});
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"all http request done!");
NSLog(@"UI update in main thread!");
});
}
我们再来看一下结果:
2017-07-20 11:44:01.744 TestMutiRequest[1381:90462] requestcommand4 in group thread:<NSThread: 0x60000007bfc0>{number = 6, name = (null)}
2017-07-20 11:44:01.744 TestMutiRequest[1381:90404] requestcommand2 in group thread:<NSThread: 0x608000073880>{number = 4, name = (null)}
2017-07-20 11:44:01.744 TestMutiRequest[1381:90406] requestcommand1 in group thread:<NSThread: 0x60000007ba80>{number = 3, name = (null)}
2017-07-20 11:44:01.744 TestMutiRequest[1381:90403] requestcommand3 in group thread:<NSThread: 0x60000007bec0>{number = 5, name = (null)}
2017-07-20 11:44:01.745 TestMutiRequest[1381:90463] requestcommand5 in group thread:<NSThread: 0x60000007be80>{number = 7, name = (null)}
2017-07-20 11:44:01.745 TestMutiRequest[1381:90464] request:requestcommand4 run in thread:<NSThread: 0x60000007c440>{number = 8, name = (null)}
2017-07-20 11:44:01.746 TestMutiRequest[1381:90465] request:requestcommand2 run in thread:<NSThread: 0x60000007c4c0>{number = 9, name = (null)}
2017-07-20 11:44:01.746 TestMutiRequest[1381:90466] request:requestcommand1 run in thread:<NSThread: 0x60000007c540>{number = 10, name = (null)}
2017-07-20 11:44:01.746 TestMutiRequest[1381:90464] request:requestcommand3 run in thread:<NSThread: 0x60000007c440>{number = 8, name = (null)}
2017-07-20 11:44:01.746 TestMutiRequest[1381:90467] request:requestcommand5 run in thread:<NSThread: 0x608000073ec0>{number = 11, name = (null)}
2017-07-20 11:44:01.751 TestMutiRequest[1381:90356] requset:requestcommand4 done!
2017-07-20 11:44:01.821 TestMutiRequest[1381:90356] requset:requestcommand3 done!
2017-07-20 11:44:02.817 TestMutiRequest[1381:90356] requset:requestcommand1 done!
2017-07-20 11:44:03.796 TestMutiRequest[1381:90356] requset:requestcommand5 done!
2017-07-20 11:44:07.817 TestMutiRequest[1381:90356] requset:requestcommand2 done!
2017-07-20 11:44:07.818 TestMutiRequest[1381:90356] all http request done!
2017-07-20 11:44:07.818 TestMutiRequest[1381:90356] UI update in main thread!
这样的结果就是我们希望得到的了,但是这种方式会使调用的线程数增加了一倍,由原来的5个变成了10个,这是因为我们把请求方法改成了同步的,但是网络请求是在其他线程执行的!系统分配给执行httpRequest2的线程必须等待进行具体网络请求的线程执行结束后再能继续执行,否则继续等待,相对上一种方案来说,这个线程就是刚好多出来的线程,这在上一种方案是不存在的。也就是刚好多了一倍。
方案三:dispatch_semaphore_t(不会额外增加多一倍的线程)
使用信号量
- (void)testUsingGCDSemaphore{
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSArray *commandArray = @[@"requestcommand1", @"requestcommand2", @"requestcommand3", @"requestcommand4", @"requestcommand5"];
NSInteger commandCount = [commandArray count];
//代表http访问返回的数量
//这里模仿的http请求block块都是在同一线程(主线程)执行返回的,所以对这个变量的访问不存在资源竞争问题,故不需要枷锁处理
//如果网络请求在不同线程返回,要对这个变量进行枷锁处理,不然很会有资源竞争危险
__block NSInteger httpFinishCount = 0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//demo testUsingSemaphore方法是在主线程调用的,不直接调用遍历执行,而是嵌套了一个异步,是为了避免主线程阻塞
NSLog(@"start all http dispatch in thread: %@", [NSThread currentThread]);
[commandArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self httpRequest:nil param:@{commandKey : obj} completion:^(id response) {
//全部请求返回才触发signal
if (++httpFinishCount == commandCount) {
dispatch_semaphore_signal(sem);
}
}];
}];
//如果全部请求没有返回则该线程会一直阻塞
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"all http request done! end thread: %@", [NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"UI update in main thread!");
});
});
}
这是种可行的方法,思路很简单:任务分发线程进行等待,所有网络请求成功返回后才发送信号量,任务分发线程继续执行。直接上结果:
2017-07-20 11:58:45.498 TestMutiRequest[1469:105980] start all http dispatch in thread: <NSThread: 0x608000260680>{number = 3, name = (null)}
2017-07-20 11:58:45.499 TestMutiRequest[1469:106008] request:requestcommand3 run in thread:<NSThread: 0x60000007ec80>{number = 6, name = (null)}
2017-07-20 11:58:45.499 TestMutiRequest[1469:105983] request:requestcommand2 run in thread:<NSThread: 0x608000260c00>{number = 5, name = (null)}
2017-07-20 11:58:45.499 TestMutiRequest[1469:105981] request:requestcommand1 run in thread:<NSThread: 0x60000007e000>{number = 4, name = (null)}
2017-07-20 11:58:45.499 TestMutiRequest[1469:106009] request:requestcommand4 run in thread:<NSThread: 0x608000260d40>{number = 7, name = (null)}
2017-07-20 11:58:45.499 TestMutiRequest[1469:106010] request:requestcommand5 run in thread:<NSThread: 0x608000260b80>{number = 8, name = (null)}
2017-07-20 11:58:45.519 TestMutiRequest[1469:105944] requset:requestcommand1 done!
2017-07-20 11:58:47.500 TestMutiRequest[1469:105944] requset:requestcommand4 done!
2017-07-20 11:58:49.559 TestMutiRequest[1469:105944] requset:requestcommand3 done!
2017-07-20 11:58:50.558 TestMutiRequest[1469:105944] requset:requestcommand5 done!
2017-07-20 11:58:52.571 TestMutiRequest[1469:105944] requset:requestcommand2 done!
2017-07-20 11:58:52.572 TestMutiRequest[1469:105980] all http request done! end thread: <NSThread: 0x608000260680>{number = 3, name = (null)}
2017-07-20 11:58:52.572 TestMutiRequest[1469:105944] UI update in main thread!
结论:
从效率和资源使用的角度来看,最后一种只使用信号量的方法是最好的,但是却有点使用一个外部变量来保存执行次数的嫌疑。
另外本文的思路不仅适用于网络请求这种场景,其他需要异步执行的类似场景也是适用的,比如数据库操作等。
大家有什么好的方法也可以一起来讨论。