GCD is used to handle multithreading in iOS, its a low level api used for managing operations. It help developers to improve their app response by running some expensive tasks in the background.
GCD is build on top of threads, and under the hood it shares a thread poll. Blocks of code will be added to Dispatch queue, and then GCD decides which thread to execute the blocks of code.
Those tasks will be picked up by order, first in first out, but the order of completion depends on the Queue type.
Queues are either serial or concurrent. Serial Queues allows only 1 task to run at a specific time, the execution time is controlled by GCD. While in Concurrent queues, multiple tasks can run at the same time, tasks will start in the order you add them, but the finish is not ordered
3 main types of queues are provided with GCD:
- Main queues: those queues run on the main thread and are serial queues. This is useful to update the UI after a task is done.
- Global Queues: those are shared by the whole system, they are concurrent queues. This is useful for non UI tasks in background.
- Custom Queues: can be either serial or concurrent, the developer can create them. This is useful for serial background work.
Global queues consists of 4 queues each with different priorities:
- Background(lowest priority).
When Global Queues receives a task, we don’t specify the priority, we specify the Quality of Service(QoS) property, which will indicate the importance of each task and inform the GCD to determine the priority of each task.
QoS consist of 4 classes:
- User interactive: This must run on the main thread, use it for small UI updates or handling small workloads in order to have a great user experience. Tasks here must end immediately.
- User initial: Use this when a user starts a task from the UI, and he’s waiting for fast results , and for tasks that are required to continue UI
- Utility: This is used for long running tasks , like API calls.
- Background: Use this for any work the user is not aware of. like prefetching data, or any work that doesn’t require any user interaction and tasks not related to time condition.