第三章 3.2.7 dispatch_barrier_async

为高效的访问,读取处理追加到Concurrent Dispatch Queue,写入处理在任何一个读取操作都没有执行的状态下,追加到Serial Dispatch Queue。类似这样的需求,我们可以使用dispatch_barrier_async。

dispatch_queue_t queue = dispatch_queue_create("com.example.gdc.ForBarrier", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{
    NSLog(@"reading1");
});

dispatch_async(queue, ^{
    NSLog(@"reading2");
});

dispatch_async(queue, ^{
    NSLog(@"reading3");
});

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

dispatch_async(queue, ^{
    NSLog(@"reading4");
});

dispatch_async(queue, ^{
    NSLog(@"reading5");
});

输出:
2018-07-23 22:38:16.498997+0800 Demo[9100:359307] reading3
2018-07-23 22:38:16.498997+0800 Demo[9100:359308] reading1
2018-07-23 22:38:16.498997+0800 Demo[9100:359311] reading2
2018-07-23 22:38:16.500972+0800 Demo[9100:359308] writing
2018-07-23 22:38:16.501812+0800 Demo[9100:359308] reading4
2018-07-23 22:38:16.501831+0800 Demo[9100:359311] reading5

说明:
dispatch_barrier_async函数会等待该函数之前追加到Concurrent Dispatch Queue上的并行执行的处理全部结束后,再将指定的处理追加到该Concurrent Dispatch Queue中,dispatch_barrier_async函数追加的处理执行完毕后,该函数之后追加到Concurrent Dispatch Queue的处理才又开始并行处理。

你可能感兴趣的:(第三章 3.2.7 dispatch_barrier_async)