新任务不等待GCD Barriers

New tasks don't wait for GCD Barriers

我了解了一些关于 GCD 障碍的知识并想检查这些信息(来自 Apple docs):

Any blocks submitted after the barrier block are not executed until the barrier block completes.

通过此代码:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
for (int i = 0; i < 500, i++) {
  dispatch_async(queue, ^{
    NSLog("%d", i);
  }
  if ((i % 50) == 0) {
    dispatch_barrier_async(queue, ^{
      for (int j = 0; j < 5; j++) {
        [NSThread sleepForTimeInterval:1];
        NSLog(@"Barrier!");
      }
    });
  }
}

我原以为每计数 50 次,队列就会停止 5 秒,但事实并非如此。相反,障碍与其他任务并行执行,并且所有任务都会立即执行,尽管存在障碍。是文档错了还是我误解了什么?提前致谢

您似乎误读了文档中的下一段

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_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);

不会充当障碍物,而是正常的 dispatch_async