并发 (三):Group Dispatch and DIY Dispatch

36 篇文章 0 订阅
12 篇文章 0 订阅

将GCD任务集合起来

目的:将代码块集合到一起,确保他们在GCD机制下,一个接一个的执行,就像是相互依靠。
解决方法:dispatch_group_create 来建立集合

先了解下Group的四个方法:

  1. dispatch_group_create
  2. dispatch_group_async
  3. dispatch_group_notify
  4. dispatch_group_release

1和4搭配使用,2要指定调度队列,3是允许你在添加到group中的所有任务执行完之后,汇总再执行别的任务。

实例:有三个方法我们想依次调用,都调用完了,然后再给用户一个提示信息。

 dispatch_group_t taskGroup = dispatch_group_create();
    dispatch_queue_t mainQueue = dispatch_get_main_queue();

    dispatch_group_async(taskGroup, mainQueue, ^{
        [self reloadTableView];
    });
    dispatch_group_async(taskGroup, mainQueue, ^{
        [self reloadScrollView];
    });
    dispatch_group_async(taskGroup, mainQueue, ^{
        [self reloadImageView];
    });
    dispatch_group_notify(taskGroup, mainQueue, ^{
        /**
         *  自己随便写点什么提示消息吧
         */
    });

    dispatch_release(taskGroup);//ARC下可以省略

C函数实现方法:略,不想写了

创建你自己的GCD调度队列

这样创建的是serial queue(串行队列),它将会用到:
dispatch_queue_create、dispatch_release、dispatch_async
其中create方法的第一个参数是一个C的字符串类型char*,第二个参数为0。
而dispatch_async在这里使用的原因是:dispatch_sync是FIFO原则执行,而一个队列上的并发任务不会在主线程上执行,这个机制可以令串行队列更加高效。


dispatch_queue_t firstSerialQueue =
dispatch_queue_create("com.company.product.serialQueue1", 0);

dispatch_async(firstSerialQueue, ^{
    NSUInteger counter = 0;
    for (counter = 0; counter<5; counter++) {
        NSLog(@"First iteration, counter = %lu",(unsigned long)counter);
    }
});

dispatch_async(firstSerialQueue, ^{
    NSUInteger counter = 0;
    for (counter = 0; counter<5; counter++) {
        NSLog(@"Second iteration, counter = %lu",(unsigned long)counter);
    }
});

dispatch_async(firstSerialQueue, ^{
    NSUInteger counter = 0;
    for (counter = 0; counter<5; counter++) {
        NSLog(@"Third iteration, counter = %lu",(unsigned long)counter);
    }
});

dispatch_release(firstSerialQueue);//ARC下不需要

打印出来的结果是

First iteration, counter = 0
First iteration, counter = 1
First iteration, counter = 2
First iteration, counter = 3
First iteration, counter = 4
Second iteration, counter = 0
Second iteration, counter = 1
Second iteration, counter = 2
Second iteration, counter = 3
Second iteration, counter = 4
Third iteration, counter = 0
Third iteration, counter = 1
Third iteration, counter = 2
Third iteration, counter = 3
Third iteration, counter = 4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值