多个网络请求成功返回再执行另外任务的思路分析(iOS)

前言

今天我们来讨论一个经常出现的需求场景,也是一个老话题。在开发中我们往往会遇到需要进行多个网络请求,并且需要多个网络请求成功返回后再做其他事的场景。比如同一个界面显示的内容需要用到两个网络接口,而需求又希望成功返回两个接口的数据再进行页面展示;又比如喜欢挖坑的后台同学就只提供了返回一条数据的接口,但需求却希望我们在一个界面同时显示几条数据的情况。

正题

我们不讨论什么执行完一个请求再执行一个这种串行的低效率方法,以下分析都是在异步的基础上进行的。
废话少说,直奔正题!先上个网络请求的模拟代码。

//模拟一个网络请求方法 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)testUsingGroup1{
    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-04-29 21:49:27.336 TestMutiRequest[1345:82575] requestcommand2 in group thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-04-29 21:49:27.336 TestMutiRequest[1345:82576] requestcommand1 in group thread:<NSThread: 0x60000007f2c0>{number = 3, name = (null)}
2017-04-29 21:49:27.336 TestMutiRequest[1345:82578] requestcommand3 in group thread:<NSThread: 0x608000263c00>{number = 5, name = (null)}
2017-04-29 21:49:27.336 TestMutiRequest[1345:82638] requestcommand4 in group thread:<NSThread: 0x600000262b00>{number = 6, name = (null)}
2017-04-29 21:49:27.336 TestMutiRequest[1345:82575] requestcommand5 in group thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-04-29 21:49:27.336 TestMutiRequest[1345:82576] request:requestcommand2 run in thread:<NSThread: 0x60000007f2c0>{number = 3, name = (null)}
2017-04-29 21:49:27.337 TestMutiRequest[1345:82639] request:requestcommand1 run in thread:<NSThread: 0x608000264000>{number = 7, name = (null)}
2017-04-29 21:49:27.337 TestMutiRequest[1345:82578] request:requestcommand3 run in thread:<NSThread: 0x608000263c00>{number = 5, name = (null)}
2017-04-29 21:49:27.337 TestMutiRequest[1345:82638] request:requestcommand4 run in thread:<NSThread: 0x600000262b00>{number = 6, name = (null)}
2017-04-29 21:49:27.338 TestMutiRequest[1345:82575] request:requestcommand5 run in thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-04-29 21:49:27.391 TestMutiRequest[1345:82507] all http request done!
2017-04-29 21:49:27.429 TestMutiRequest[1345:82507] UI update in main thread!
2017-04-29 21:49:27.432 TestMutiRequest[1345:82507] requset:requestcommand2 done!
2017-04-29 21:49:27.435 TestMutiRequest[1345:82507] requset:requestcommand3 done!
2017-04-29 21:49:27.437 TestMutiRequest[1345:82507] requset:requestcommand4 done!
2017-04-29 21:49:28.347 TestMutiRequest[1345:82507] requset:requestcommand5 done!
2017-04-29 21:49:35.399 TestMutiRequest[1345:82507] requset:requestcommand1 done!

注意这里:

2017-04-29 21:49:27.338 TestMutiRequest[1345:82575] request:requestcommand5 run in thread:<NSThread: 0x600000262a40>{number = 4, name = (null)}
2017-04-29 21:49:27.391 TestMutiRequest[1345:82507] all http request done!
2017-04-29 21:49:27.429 TestMutiRequest[1345:82507] UI update in main thread!
2017-04-29 21:49:27.432 TestMutiRequest[1345:82507] requset:requestcommand2 done!

结果很明显,并不能得出我们需要的结果!!
问题究竟出现哪呢?!!
让我们在回顾一下group的概念,group的设计就是为了方便我们执行完一系列的任务之后再执行其他的任务,但是不能忽视的是,这里的任务是有要求的,这里的任务必须要是同步执行的!!如果任务是异步的,group只会执行完任务里面异步之前的代码以及分发异步任务就返回了!!也就代表分发group的当前这个任务完成了!但事实却是这个任务的一部分子任务在其他线程执行了,而且不一定已执行结束返回。
问题分析到这里,理所当然的就会出现以上结果的问题。
解决的方案也很自然想法了,就是想办法使分发到group的任务是同步执行的。
顺便提一点,虽然任务未能顺利完成,但我们可以注意到GCD实现的一些细节,在这里group到另外异步方法的执行,GCD并没有重新创建新的线程,而是重用了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);
}

testUsingGroup方法也相应改成对httpRequest2方法的调用

- (void)testUsingGroup2{
    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-04-29 22:02:01.744 TestMutiRequest[1381:90462] requestcommand4 in group thread:<NSThread: 0x60000007bfc0>{number = 6, name = (null)}
2017-04-29 22:02:01.744 TestMutiRequest[1381:90404] requestcommand2 in group thread:<NSThread: 0x608000073880>{number = 4, name = (null)}
2017-04-29 22:02:01.744 TestMutiRequest[1381:90406] requestcommand1 in group thread:<NSThread: 0x60000007ba80>{number = 3, name = (null)}
2017-04-29 22:02:01.744 TestMutiRequest[1381:90403] requestcommand3 in group thread:<NSThread: 0x60000007bec0>{number = 5, name = (null)}
2017-04-29 22:02:01.745 TestMutiRequest[1381:90463] requestcommand5 in group thread:<NSThread: 0x60000007be80>{number = 7, name = (null)}
2017-04-29 22:02:01.745 TestMutiRequest[1381:90464] request:requestcommand4 run in thread:<NSThread: 0x60000007c440>{number = 8, name = (null)}
2017-04-29 22:02:01.746 TestMutiRequest[1381:90465] request:requestcommand2 run in thread:<NSThread: 0x60000007c4c0>{number = 9, name = (null)}
2017-04-29 22:02:01.746 TestMutiRequest[1381:90466] request:requestcommand1 run in thread:<NSThread: 0x60000007c540>{number = 10, name = (null)}
2017-04-29 22:02:01.746 TestMutiRequest[1381:90464] request:requestcommand3 run in thread:<NSThread: 0x60000007c440>{number = 8, name = (null)}
2017-04-29 22:02:01.746 TestMutiRequest[1381:90467] request:requestcommand5 run in thread:<NSThread: 0x608000073ec0>{number = 11, name = (null)}
2017-04-29 22:02:01.751 TestMutiRequest[1381:90356] requset:requestcommand4 done!
2017-04-29 22:02:01.821 TestMutiRequest[1381:90356] requset:requestcommand3 done!
2017-04-29 22:02:02.817 TestMutiRequest[1381:90356] requset:requestcommand1 done!
2017-04-29 22:02:03.796 TestMutiRequest[1381:90356] requset:requestcommand5 done!
2017-04-29 22:02:07.817 TestMutiRequest[1381:90356] requset:requestcommand2 done!
2017-04-29 22:02:07.818 TestMutiRequest[1381:90356] all http request done!
2017-04-29 22:02:07.818 TestMutiRequest[1381:90356] UI update in main thread!

这个结果就是我们预期希望得到的!
但是不能高兴的太早,这个方法需要实现了我们的需求,但是确实存在问题的。我们可以看一下当前的线程情况。整整比上一种不可行方案多出了一倍的线程数(5条线程->10条线程)!!
这是怎么发生的呢?刚好是因为我们把请求方法改成了同步的,但是网络请求是在其他线程执行的!系统分配给执行httpRequest2的线程必须等待进行具体网络请求的线程执行结束后再能继续执行,否则继续等待,相对上一种方案来说,这个线程就是刚好多出来的线程,这在上一种方案是不存在的。也就是刚好多了一倍。虽然有代价,但是我们的任务也算顺利完成了。

不额外增加多一倍线程的方法(dispatch_semaphore_t)

使用信号量

- (void)testUsingSemaphore{
    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-04-29 22:25:45.498 TestMutiRequest[1469:105980] start all http dispatch in thread: <NSThread: 0x608000260680>{number = 3, name = (null)}
2017-04-29 22:25:45.499 TestMutiRequest[1469:106008] request:requestcommand3 run in thread:<NSThread: 0x60000007ec80>{number = 6, name = (null)}
2017-04-29 22:25:45.499 TestMutiRequest[1469:105983] request:requestcommand2 run in thread:<NSThread: 0x608000260c00>{number = 5, name = (null)}
2017-04-29 22:25:45.499 TestMutiRequest[1469:105981] request:requestcommand1 run in thread:<NSThread: 0x60000007e000>{number = 4, name = (null)}
2017-04-29 22:25:45.499 TestMutiRequest[1469:106009] request:requestcommand4 run in thread:<NSThread: 0x608000260d40>{number = 7, name = (null)}
2017-04-29 22:25:45.499 TestMutiRequest[1469:106010] request:requestcommand5 run in thread:<NSThread: 0x608000260b80>{number = 8, name = (null)}
2017-04-29 22:25:45.519 TestMutiRequest[1469:105944] requset:requestcommand1 done!
2017-04-29 22:25:47.500 TestMutiRequest[1469:105944] requset:requestcommand4 done!
2017-04-29 22:25:49.559 TestMutiRequest[1469:105944] requset:requestcommand3 done!
2017-04-29 22:25:50.558 TestMutiRequest[1469:105944] requset:requestcommand5 done!
2017-04-29 22:25:52.571 TestMutiRequest[1469:105944] requset:requestcommand2 done!
2017-04-29 22:25:52.572 TestMutiRequest[1469:105980] all http request done! end thread: <NSThread: 0x608000260680>{number = 3, name = (null)}
2017-04-29 22:25:52.572 TestMutiRequest[1469:105944] UI update in main thread!

结论:
从效率和资源使用的角度来看,最后一种只使用信号量的方法是最好的,但是却有点使用一个外部变量来保存执行次数的嫌疑。
另外本文的思路不仅适用于网络请求这种场景,其他需要异步执行的类似场景也是适用的,比如数据库操作等。
个人水平有限,如果你有更好的方案或者觉得不对的地方,随时欢迎在评论留言交流学习!!

最后附上demo地址:
https://github.com/Calvix-Xu/TestMultiRequest.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,997评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,603评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,359评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,309评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,346评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,258评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,122评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,970评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,403评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,596评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,769评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,464评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,075评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,705评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,848评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,831评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,678评论 2 354

推荐阅读更多精彩内容