美文网首页iOS那些坑
如何同步若干个异步调用?(如根据若干个url异步加载多张图片,然

如何同步若干个异步调用?(如根据若干个url异步加载多张图片,然

作者: zgsddzwj | 来源:发表于2017-03-21 11:49 被阅读29次

    GCD:
    使用Dispatch Group追加block到Global Group Queue,这些block如果全部执行完毕,就会执行Main Dispatch Queue中的结束处理的block。
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{ /*加载图片1 / });
    dispatch_group_async(group, queue, ^{ /
    加载图片2 / });
    dispatch_group_async(group, queue, ^{ /
    加载图片3 */ });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // 合并图片
    });

    需要注意的:dispatch_group_wait是同步的所以不能放在主线程执行。
    补充: dispatch_group会等和它关联的所有的dispatch_queue_t上的任务都执行完毕才会发出同步信号(dispathc_group_notify的代码块block会被执行,group_wait会结束等待)。也就是说一个group可以关联多个任务队列;下面给出示例:

    • (void)groupSync2
      {
      dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next1", DISPATCH_QUEUE_CONCURRENT);
      dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
      dispatch_group_t dispatchGroup = dispatch_group_create();
      dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
      sleep(5);
      NSLog(@"任务一完成");
      });
      dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
      sleep(6);
      NSLog(@"任务二完成");
      });
      dispatch_group_async(dispatchGroup, globalQueue, ^{
      sleep(10);
      NSLog(@"任务三完成");
      });
      dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
      NSLog(@"notify:任务都完成了");
      });
      }
      NSOperation:
      // 创建队列
      NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
      // 添加操作
      NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
      NSLog(@"download1----%@", [NSThread currentThread]);
      }];
      NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
      NSLog(@"download2----%@", [NSThread currentThread]);
      }];
      NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
      NSLog(@"download3----%@", [NSThread currentThread]);
      }];
      // 设置依赖(保证op3在op1和op2都执行完之后再执行)
      [op3 addDependency:op1];
      [op3 addDependency:op2];
      [op1 start];
      [op2 start];
      [op3 start];

    相关文章

      网友评论

        本文标题:如何同步若干个异步调用?(如根据若干个url异步加载多张图片,然

        本文链接:https://www.haomeiwen.com/subject/apbwnttx.html