Grand Central Dispatch Part 2

Aug 6, 2021

Part 2 : DispatchGroup, DispatchSemaphore

So we've seen how to use GCD with one task, but how to deal with multiple tasks ? This is where DispatchGroup is useful.

DispatchGroup

We start by initializing a DispatchGroup, then provide it as an argument to the async method of our dispatch queue.

For example : 

let dispatchGroup = DispatchGroup() someQueue.async(group: group) { /* some work */ } someQueue.async(group: group) { /* some other work */ } someOtherQueue.async(group: group) { /* another work */ }

We can see that dispatchGroup is not attached to a single dispatch. That mean we can submit multiple tasks to multiples queues.

When all tasks are done, DispatchGroup will notify us.

Note that notify take a dispatch queue as a parameter, that mean the closure will be executed in the specified one.

Let's see a more concrete example, for each task, we enter the group, and leave it for each completed task.

See how we use the enter and leave, if we forgot to leave after entering, the app will hang forever !

DispatchSemaphore

Ok, we can work with multiple tasks, but imagine that we need to prevent tasks to access the same shared resource, like a read/write a file ? Or limit how many downloads can happen at once ? Using DispatchSemaphore can help us with that.

For example :

Here, the app will loop in our `for` statement 7 times, and during the loop, will wait 2 seconds before running again.