iOS系统GCD学习(4):dispatch_group2

本文详细介绍了Grand Central Dispatch (GCD) 中dispatch_apply与dispatch_barrier_async的使用方法。dispatch_apply允许并行执行任务并等待所有任务完成,而dispatch_barrier_async确保在前面的任务完成后才开始执行,并阻止后续任务在其之前运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dispatch_apply的使用

  对于同步执行,GCD提供了一个简化方法叫做dispatch_apply。这个函数调用单一block多次,并平行运算,然后等待所有运算结束,就像我们想要的那样:

1
2
3
4
5
dispatch_queue_t queue = dispatch_get_global_qeueue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     dispatch_apply([array count], queue, ^( size_t index){
         [self doSomethingIntensiveWith:[array objectAtIndex:index]];
     });
     [self doSomethingWith:array];

  这很棒,但是异步咋办?dispatch_apply函数可是没有异步版本的。但是我们使用的可是一个为异步而生的API啊!所以我们只要用dispatch_async函数将所有代码推到后台就行了:

1
2
3
4
5
6
7
dispatch_queue_t queue = dispatch_get_global_qeueue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
     dispatch_apply([array count], queue, ^( size_t index){
         [self doSomethingIntensiveWith:[array objectAtIndex:index]];
     });
     [self doSomethingWith:array];
});

dispatch_barrier_async的使用

  dispatch_barrier_async是在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行。
  例子代码如下:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
   
dispatch_queue_t queue = dispatch_queue_create( "gcdtest.rongfzh.yc" , DISPATCH_QUEUE_CONCURRENT); 
dispatch_async(queue, ^{ 
     [NSThread sleepForTimeInterval:2]; 
     NSLog(@ "dispatch_async1" ); 
}); 
dispatch_async(queue, ^{ 
     [NSThread sleepForTimeInterval:4]; 
     NSLog(@ "dispatch_async2" ); 
}); 
dispatch_barrier_async(queue, ^{ 
     NSLog(@ "dispatch_barrier_async" ); 
     [NSThread sleepForTimeInterval:4]; 
   
}); 
dispatch_async(queue, ^{ 
     [NSThread sleepForTimeInterval:1]; 
     NSLog(@ "dispatch_async3" ); 
});

  打印结果:

1
2
3
4
2012-09-25 16:20:33.967 gcdTest[45547:11203] dispatch_async1
2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_async2
2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_barrier_async
2012-09-25 16:20:40.970 gcdTest[45547:11303] dispatch_async3

  请注意执行的时间,可以看到执行的顺序如上所述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值