C/C++教程

iOS GCD之Barrier

本文主要是介绍iOS GCD之Barrier,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Barrier

  • 官方文档的介绍
Calls to this function always return immediately after the block is submitted and never wait for the block to be invoked. When the barrier block reaches the front of a private concurrent queue, it is not executed immediately. Instead, the queue waits until its currently executing blocks finish executing. At that point, the barrier block executes by itself. Any blocks submitted after the barrier block are not executed until the barrier block completes.

The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_async function.
  • 对Barrier的理解:将Barrier翻译成栅栏,它有两种类型的函数void dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);void dispatch_barrier_sync(dispatch_queue_t queue, dispatch_block_t block);本文以第一个函数为例介绍栅栏。根据官方文档的理解是,当将栅栏块任务添加到私有并发队列里面时,它不会立即执行,而是等待队列中正在执行的块(在Barrier任务之前添加到队列之前添加的任务)完成执行,此时,屏障块自行执行。在屏障块完成之前,在屏障块之后提交的任何块都不会执行。
  • 注意:您指定的队列应该是您使用dispatch_queue_create函数自己创建的并发队列。如果您传递给此函数的队列是串行队列或全局并发队列之一,则此函数的行为类似于dispatch_async函数。
  • 示例代码
for (int i = 0; i < 5; i++) {
    dispatch_async(queue, ^{
        NSLog(@"%d前%@",i,[NSThread currentThread]);
    });
}

dispatch_barrier_async(queue, ^{
    sleep(10);
    NSLog(@"this is a barrier,%@",[NSThread currentThread]);
});

for (int i = 0; i < 5; i++) {
    dispatch_async(queue, ^{
        NSLog(@"%d后%@",i,[NSThread currentThread]);
    });
}

结果:
2022-02-24 22:32:48.840091+0800 iOSLearn[10911:190593] 1前<NSThread: 0x6000035755c0>{number = 4, name = (null)}
2022-02-24 22:32:48.840091+0800 iOSLearn[10911:190598] 0前<NSThread: 0x600003521b00>{number = 6, name = (null)}
2022-02-24 22:32:48.840122+0800 iOSLearn[10911:190592] 3前<NSThread: 0x600003570240>{number = 8, name = (null)}
2022-02-24 22:32:48.840156+0800 iOSLearn[10911:190594] 4前<NSThread: 0x60000356c1c0>{number = 3, name = (null)}
2022-02-24 22:32:48.840169+0800 iOSLearn[10911:190596] 2前<NSThread: 0x6000035386c0>{number = 7, name = (null)}
2022-02-24 22:32:58.845375+0800 iOSLearn[10911:190598] this is a barrier,<NSThread: 0x600003521b00>{number = 6, name = (null)}
2022-02-24 22:32:58.845874+0800 iOSLearn[10911:190598] 0后<NSThread: 0x600003521b00>{number = 6, name = (null)}
2022-02-24 22:32:58.845984+0800 iOSLearn[10911:190596] 1后<NSThread: 0x6000035386c0>{number = 7, name = (null)}
2022-02-24 22:32:58.846081+0800 iOSLearn[10911:190668] 2后<NSThread: 0x600003538200>{number = 9, name = (null)}
2022-02-24 22:32:58.846086+0800 iOSLearn[10911:190598] 3后<NSThread: 0x600003521b00>{number = 6, name = (null)}
2022-02-24 22:32:58.846169+0800 iOSLearn[10911:190669] 4后<NSThread: 0x600003578900>{number = 10, name = (null)}
  • Barrier的应用:读写锁(待补充)
这篇关于iOS GCD之Barrier的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!