多线程 - dispatch_barrier_async 使用及解析

来源:互联网 发布:apache ant.jar maven 编辑:程序博客网 时间:2024/05/17 02:57

示例

- (void) testBarrierBlock {    dispatch_queue_t myConcurrentQueue = dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT); // 需要自己创建    dispatch_async(myConcurrentQueue, ^{  // 1.2是并行的        NSLog(@"dispatch test 1");    });    dispatch_async(myConcurrentQueue, ^{        NSLog(@"dispatch test 2");    });    dispatch_barrier_async(myConcurrentQueue, ^{  // 等1.2都执行完便会执行此方法,此时便会将线程延迟直至barrier执行完毕方可        NSLog(@"dispatch barrier");    });    dispatch_async(myConcurrentQueue, ^{   // 这两个是同时执行的        NSLog(@"dispatch test 3");    });    dispatch_async(myConcurrentQueue, ^{        NSLog(@"dispatch test 4");    });}

文档解析:

dispatch_barrier_async

Using Barriers:

A dispatch barrier allows you to create a synchronization point within a concurrent dispatch queue.When it encounters a barrier, a concurrent queue delays the execution of the barrier block (or any further blocks)until all blocks submitted before the barrier finish executing. At that point, the barrier block executes by itself.Upon completion, the queue resumes its normal execution behavior.

一个dispatch barrier允许你在一个并行队列中创建一个同步点。当在队列中遇到这个barrier时,这个barrier block便会延迟执行(同时所有在其后的block都会延迟),直至所有在barrier之前的block执行完成。这时,这个barrier block便会执行。之后队列便恢复正常执行。


Discussion

Calls to this function always return immediately after the block has been 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.

调用这个函数总是会在这个block被提交后立刻返回,并且不会等到block被触发。当这个barrier block到达私有并行 队列最前端时,它不是立即执行。恰恰相反,这个队列会一直等待当前正在执行的队列执行完成。此时barrier block才会执行。所有barrier block之后提交的block会等到barrier block执行结束后才会执行。


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.

这里你指定的并行队列应该是自己通过dispatch_queue_cretate创建的。如果你传的是一个串行或是一个全局的并行队列,那这个函数便等同于dispatch_async 函数效果了。

0 0