首页 > 代码库 > dispatch_barrier_async

dispatch_barrier_async

代码:

dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{
    NSLog(@"Before Barrier Block - 1");
});
dispatch_async(queue, ^{
    NSLog(@"Before Barrier Block - 2");
});
dispatch_async(queue, ^{
    NSLog(@"Before Barrier Block - 3");
});
dispatch_async(queue, ^{
    NSLog(@"Before Barrier Block - 4");
});
dispatch_async(queue, ^{
    NSLog(@"Before Barrier Block - 5");
});

dispatch_barrier_async(queue, ^{
    NSLog(@"Barrier Block");
});

dispatch_async(queue, ^{
    NSLog(@"After Barrier Block - 1");
});
dispatch_async(queue, ^{
    NSLog(@"After Barrier Block - 2");
});
dispatch_async(queue, ^{
    NSLog(@"After Barrier Block - 3");
});
dispatch_async(queue, ^{
    NSLog(@"After Barrier Block - 4");
});
dispatch_async(queue, ^{
    NSLog(@"After Barrier Block - 5");
}); 

可能的输出:

Before Barrier Block - 1
Before Barrier Block - 2
Before Barrier Block - 3
Before Barrier Block - 5
Before Barrier Block - 4
Barrier Block
After Barrier Block - 1
After Barrier Block - 3
After Barrier Block - 2
After Barrier Block - 5
After Barrier Block - 4

备注:

dispatch_barrier_async用于在同一个并发队列中,同步多个并发操作

dispatch_barrier_async