天天看點

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