美文网首页
GCD(Using Barriers)

GCD(Using Barriers)

作者: _涼城 | 来源:发表于2016-07-17 08:38 被阅读77次

Using Barriers

       A dispatch barrier允许您在并发调度队列(concurrent dispatch queue)中创建一个同步点。当它遇到一个barrier,并发队列(a concurrent queue)延迟执行的(the barrier block),直到所有Block完成执行。完成后,队列恢复其正常的执行行为。

1.提交异步执行的障碍块,并立即返回。

void dispatch_barrier_async( dispatch_queue_t queue, dispatch_block_t block);

      再访问数据库或文件时,使用 Serial Dispatch Queue 可避免数据竞争的问题。也就是说,为了更高效地进行访问,读取处理追加到 Concurrent Dispatch Queue 中,写入处理在任意一个读取处理没有执行的状态下,追到 Serial Dispatch Queue 中。(在写入处理结束前,读取处理不可执行)。

      虽然利用Dispatch Group 和 Dispatch_set_target_queue 函数也可实现,但是源代码会很复杂。GCD 提供了更好的解决办法--dispatch_barrier_async 函数。该函数同 dispatch_queue_create 函数生成的 Concurrent Dispatch Queue 一起使用。

dispatch_queue_t queue = dispatch_queue_create(

     "com.example.gcd.ForBarrier",DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue,blk0_for_reading);

dispatch_async(queue,blk1_for_reading);

dispatch_async(queue,blk2_for_reading);

//同时执行一个

dispatch_barrier_async(queue,blk_for_writing);

dispatch_async(queue,blk3_for_reading);

dispatch_async(queue,blk4_for_reading);


2.为执行提交一个barrier Block对象,并等待该Block完成。

void dispatch_barrier_sync( dispatch_queue_t queue, dispatch_block_t block);

      向a dispatch queue提交一个a barrier block,用于同步执行。不像dispatch_barrier_async,这个函数不返回直到a barrier block已经完成。调用此函数并针对死锁的 dispatch queue。

      当a barrier block到达一个专用concurrent queue的前面时,它不会立即执行。相反,队列等待,直到它的当前执行的Block完成执行。在这一点上,队列本身执行barrier block。在barrier block未执行之前提交的任何Block直到Block完成为止。

相关文章

  • GCD(Using Barriers)

    Using Barriers A dispatch barrier允许您在并发调度队列(concurrent...

  • 2018-09-29

    #include using namespace std; int main() {int gcd(int x,i...

  • 【翻译】用GCD实现同步机制

    原文发表于humancode.us,地址是Using GCD Queues For Synchronization...

  • barriers

    这些天,开始陆续的在日记本上记录、串写几个字。 自己似乎意识到一个非常恐怖的真相,难道这一切、这些安排、这些计划,...

  • 2018-05-08

    PERCEPTIONS OF INTERNATIONAL TRADE BARRIERS: EMPIRICALSTU...

  • 人工智能应用研究快讯 2021-11-13

    Facilitators and Barriers of Artificial Intelligence Adop...

  • 【译】同步使用GCD队列(Using GCD Queues Fo

    这是GCD介绍的第二篇 在我之前的文章中,我们已经学习过了在异步的程序中竞态条件是一个很常见的问题。就是当一份数据...

  • GCD-3 Using Dispatch Groups

    本文是本人自己辛苦翻译的,请转载的朋友注明,翻译于Z.MJun的简书 ,感谢!<翻译不容易啊> 完成翻译于2016...

  • How to Write A Lot

    Chapter 2: Specious Barriers to Writing a Lot Writing is ...

  • 2020-12-29

    This is the year we need to pull down these barriers that...

网友评论

      本文标题:GCD(Using Barriers)

      本文链接:https://www.haomeiwen.com/subject/xccujttx.html