GCD_dispatch_barrier_async

GCD_dispatch_barrier_async

在访问数据库时使用Serial Dispatch Queue队列时可避免数据竞争问题。写入处理确实不可以和其他的写入和读取处理并行执行,但是读取处理与读取处理可以并行执行。在3用dispatch_barrier_async

例如:

dispatch_queue_t concurrentQueue1= dispatch_queue_create("www.goole.com", DISPATCH_QUEUE_CONCURRENT);
    
    /********************模拟读取操作********************/
     dispatch_async(concurrentQueue1, ^{
         for (int i=0; i<1000; i++) {
             int index=arc4random()%12;
             NSLog(@"读取任务-%@",self.array[index]);
         }
     });
     dispatch_async(concurrentQueue1, ^{
         for (int i=0; i<1000; i++) {
             int index=arc4random()%12;
             NSLog(@"读取任务二%@",self.array[index]);
         }
     });
     dispatch_async(concurrentQueue1, ^{
         for (int i=0; i<1000; i++) {
             int index=arc4random()%12;
             NSLog(@"读取任务三%@",self.array[index]);
         }
    });
    
    
    /********************模拟写入操作********************/
    dispatch_barrier_async(concurrentQueue1, ^{
        [self.array removeAllObjects];
        [self.array addObjectsFromArray:@[@"aaa",@"bbb",@"ccc",@"ddd",@"eee",@"qqq",@"ccc",@"fff",@"ggg",@"rrr",@"bbb",@"jjj"]];
    });

    
    
    
    dispatch_async(concurrentQueue1, ^{
        for (int i=0; i<100; i++) {
            int index=arc4random()%12;
            NSLog(@"读取任务四%@",self.array[index]);
        }
    });
    dispatch_async(concurrentQueue1, ^{
        for (int i=0; i<100; i++) {
            int index=arc4random()%12;
            NSLog(@"读取任务五%@",self.array[index]);
        }
    });
    dispatch_async(concurrentQueue1, ^{
        for (int i=0; i<100; i++) {
            int index=arc4random()%12;
            NSLog(@"读取任务六%@",self.array[index]);
        }
    });
    
//结论:打印结果会是 读取任务一二三 执行完之后 执行写入操作,写入操作执行完之后最后执行 读取任务四五六