java - 发送10个网络请求,然后再接收到所有回应之后执行后续操作,如何实现?
天蓬老师
天蓬老师 2017-04-17 16:15:12
0
21
1508

我想到的

for iOS
1.用dispatch_group实现
2.用RunLoop实现   

还有没有其他的比较好的实现方式,求关于并发编程的文章.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(21)
刘奇

Someone said NSOperation, but I won’t say it.
But I prefer GCD. This problem can be solved using barrier:

    dispatch_queue_t queue = dispatch_queue_create("JOHNSHAW", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        NSLog(@"task 1");
        sleep(1);
    });
    dispatch_async(queue, ^{
        NSLog(@"task 2");
        sleep(1);
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"after task 1 and task 2");
        sleep(1);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"do someting else");
    });

Actually, I prefer RAC, but RAC is a heavy-duty framework after all, and not many companies use it

    RACSignal *task1 = ...;
    RACSignal *task2 = ...;
    
    [[RACSignal combineLatest:@[task1,task2]] subscribeNext:^(id x) {
        NSLog(@"after task1 and task2 ");
    }];
阿神

Use RxAndroid. A .zip method is all it takes. .

洪涛

A better way to use NSOperation is because of the addDependecy method~

洪涛

For javascript:

  1. https://github.com/caolan/async
    It’s very convenient to handle asynchronous parallelism and serialization

  2. Use jQuery’s Promise, or other libraries’ Promise implementation :)

Ty80

Learn from the map reduce method, which is similar to the idea of ​​merge sort

迷茫

Just use dispatch_group_wait and dispatch_group_notify normally.

You can also use dispatch_barrier_sync / dispatch_barrier_async to use the operation after receiving all responses as a barrier block. Then this block will wait for all network requests to complete before executing.

黄舟

I don’t know whether you are asking about Android or iOS. If it is Android, use CountDownLatch to control threads

PHPzhong

In Java, you can use the future api of the concurrent package to implement separate requests from multiple threads, and then process the results after all responses.

左手右手慢动作

for iOS
Create a serial queue for processing. Does not affect external concurrent requests.

黄舟

How to implement it in JS?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!