天天看点

iOS之GCD再谈(dispatch_barrier_async)

假如有这么一个需求,8个线程,前面4个要并行执行,执行完后执行第5个,然后在并行执行后面3个。

那么就要考虑dispatch_barrier_async了

/*
 dispatch_barrier_async 作用是在并行队列中,等待前面几个操作并行操作完成,然后执行dispatch_barrier_async中的操作,
 然后再恢复并行队列所有的执行状态,继续并行执行
 */

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //创建一个并行队列
    dispatch_queue_t concurrentQueue=dispatch_queue_create("gujinyue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(concurrentQueue, ^{
       
        NSLog(@"dispatch_1_begin");
        sleep(3);
        NSLog(@"dispatch_1_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_2_begin");
        sleep(3);
        NSLog(@"dispatch_2_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_3_begin");
        sleep(3);
        NSLog(@"dispatch_3_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_4_begin");
        sleep(3);
        NSLog(@"dispatch_4_end");
    });
    
    dispatch_barrier_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_barrier_begin");
        sleep(3);
        NSLog(@"dispatch_barrier_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_5_begin");
        sleep(3);
        NSLog(@"dispatch_5_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_6_begin");
        sleep(3);
        NSLog(@"dispatch_6_end");
    });
    
    dispatch_async(concurrentQueue, ^{
        
        NSLog(@"dispatch_7_begin");
        sleep(3);
        NSLog(@"dispatch_7_end");
    });
    
   
}

@end
           

最终效果:

2016-03-06 09:22:48.906 iOS 学习_dispatch_barrier[938:19679] dispatch_1_begin
2016-03-06 09:22:48.906 iOS 学习_dispatch_barrier[938:19682] dispatch_2_begin
2016-03-06 09:22:48.906 iOS 学习_dispatch_barrier[938:19687] dispatch_3_begin
2016-03-06 09:22:48.906 iOS 学习_dispatch_barrier[938:19691] dispatch_4_begin
2016-03-06 09:22:51.907 iOS 学习_dispatch_barrier[938:19687] dispatch_3_end
2016-03-06 09:22:51.907 iOS 学习_dispatch_barrier[938:19679] dispatch_1_end
2016-03-06 09:22:51.907 iOS 学习_dispatch_barrier[938:19682] dispatch_2_end
2016-03-06 09:22:51.908 iOS 学习_dispatch_barrier[938:19691] dispatch_4_end
2016-03-06 09:22:51.908 iOS 学习_dispatch_barrier[938:19691] dispatch_barrier_begin
2016-03-06 09:22:54.910 iOS 学习_dispatch_barrier[938:19691] dispatch_barrier_end
2016-03-06 09:22:54.911 iOS 学习_dispatch_barrier[938:19691] dispatch_5_begin
2016-03-06 09:22:54.911 iOS 学习_dispatch_barrier[938:19682] dispatch_6_begin
2016-03-06 09:22:54.911 iOS 学习_dispatch_barrier[938:19679] dispatch_7_begin
2016-03-06 09:22:57.913 iOS 学习_dispatch_barrier[938:19682] dispatch_6_end
2016-03-06 09:22:57.913 iOS 学习_dispatch_barrier[938:19691] dispatch_5_end
2016-03-06 09:22:57.913 iOS 学习_dispatch_barrier[938:19679] dispatch_7_end
           
iOS