Aleksandr Medvedev
Aleksandr Medvedev

Reputation: 8998

New tasks don't wait for GCD Barriers

I learned a bit about GCD barriers and wanted to examine this information (from Apple docs):

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

By this code:

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!");
      }
    });
  }
}

I was expecting that each 50th count, the queue will be stopped for 5 seconds, but this is not the case. Instead, barriers executes in parallel with other tasks, and all tasks despite barriers executes immediatelly. Is the docs wrong or i misunderstand somethin? Thanks in advance

Upvotes: 0

Views: 92

Answers (1)

Fonix
Fonix

Reputation: 11597

It seems you misread the next paragraph in the docs

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.

ie

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);

will not act as a barrier but instead a normal dispatch_async

Upvotes: 2

Related Questions