2
votes

Dispatch groups are a GCD feature the allows one to submit blocks to be dispatched to certain queues. Regarding the queues, the blocks are dispatched acording to the queue's type: if a queue is serial, the block is going to be executed serially in relation to that queue; if a queue is concurrent, the same happens, but concurrently.

However, regarding the group, dispatches occur serially or concurrently in relation to each other? I mean, if a group has a queue of dispatch queues and blocks to be dispatched, is the next dispatch executed only when the previous one gets finished?

1

1 Answers

8
votes

Membership in a dispatch group is independent of execution order.

A dispatch group is really just a counter, dispatch_group_enter(group) increments the counter and dispatch_group_leave(group) decrements the counter.

dispatch_group_async(group, queue, block) is a shortcut for:

dispatch_group_enter(group);
dispatch_async(queue, ^{
    block();
    dispatch_group_leave(group);
});

i.e. the execution order of blocks submitted via dispatch_group_async(group, queue, block) depends only on the queue(s) specified.

When the dispatch group counter reaches zero (the group becomes empty), all waiters in dispatch_group_wait(group) are woken up, and any blocks that have been submitted to the group via dispatch_group_notify(group, queue, block) are all async'd to their respective queues (i.e. these blocks may execute concurrently if the specified queues are concurrent/independent).