Grand Central Dispatch Part 2
Aug 6, 2021
![](https://framerusercontent.com/images/new2dwVNGdVgpajPB3bUQGYmSTc.jpg?scale-down-to=4096)
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 */ }](https://framerusercontent.com/images/IPLYX0KPWQSZ4yeVHFo0HCuDgM.jpg)
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.
![](https://framerusercontent.com/images/nZgtKpENjCsrBHEUNJkpcDcNAh0.png)
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.
![](https://framerusercontent.com/images/0Z9EbMPKTKJIaZZeI1vokujW1sw.png)
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 :
![](https://framerusercontent.com/images/oLuGHGPAJG3A0UgvmzNuwXx6vFk.png)
Here, the app will loop in our `for` statement 7 times, and during the loop, will wait 2 seconds before running again.