iOS系统GCD学习(4):dispatch_group2

dispatch_apply的使用

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


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


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

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

dispatch_barrier_async的使用

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

[cpp]  view plain copy
  1.    
  2. dispatch_queue_t queue = dispatch_queue_create("gcdtest.rongfzh.yc", DISPATCH_QUEUE_CONCURRENT);   
  3. dispatch_async(queue, ^{   
  4.     [NSThread sleepForTimeInterval:2];   
  5.     NSLog(@"dispatch_async1");   
  6. });   
  7. dispatch_async(queue, ^{   
  8.     [NSThread sleepForTimeInterval:4];   
  9.     NSLog(@"dispatch_async2");   
  10. });   
  11. dispatch_barrier_async(queue, ^{   
  12.     NSLog(@"dispatch_barrier_async");   
  13.     [NSThread sleepForTimeInterval:4];   
  14.      
  15. });   
  16. dispatch_async(queue, ^{   
  17.     [NSThread sleepForTimeInterval:1];   
  18.     NSLog(@"dispatch_async3");   
  19. });  

  打印结果:

[cpp]  view plain copy
  1. 2012-09-25 16:20:33.967 gcdTest[45547:11203] dispatch_async1  
  2. 2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_async2  
  3. 2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_barrier_async  
  4. 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、付费专栏及课程。

余额充值