Grand Central Dispatch: How to wait for the queue of blocks to complete

grand-central-dispatchios5

In iOS I have an app where I need to wait for the currently running blocks on a GCD queue to complete. I was under the impression that this line of code will do just that:

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{});

I got this tip from here:

http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/

As I understand it, this line of code will block subsequence execution until all tasks running on the global queue complete. In my code this does not appear to be happening. Can someone please suggest an approach that will do this?

Thanks,
Doug

Best Answer

The dispatch_sync() trick will only work for serial queues, which is what that tutorial is showing. The dispatch_get_global_queue() returns a concurrent queue, see it's documentation note:

Blocks submitted to these global concurrent queues may be executed concurrently with respect to each other.

To deal with a global concurrent queue you should use a group where you submit your blocks, also mentioned on that tutorial, and wait for the whole group with dispatch_group_wait().

Related Topic