You are currently viewing Grand Central Dispatch (GCD)

Grand Central Dispatch (GCD)

Introduction

Sometimes when we are developing an application we are trying to perform multiple tasks at the same time that time most of the developer-facing applications hang or freeze issues. It is a common issue. To overcome these types of issues GCD is used. 

GCD stands for Grand Central Dispatch. It is a low-level API provided by Apple to perform concurrent tasks. It helps us to improve the performance of the applications and also makes our user interface experience more elegant and smooth.

GCD manages the concurrent threads. As the power of the CPU increases, the capacity of the OS schedular of handling multiple threads simentensouly also increases. The OS scheduler manages the threads independently of each other. Each thread can execute concurrently, but it’s up to the system to decide if this happens, when this happens, and how it happens.

In a single-core application, multiple threads are managed by context switching. They run one thread and then perform a context switch, then run another thread. Multi-core devices, on the other hand, execute multiple threads at the same time via parallelism.

To understand GCD better you have to first understand a few terminologies used in GCD that are given below.

1: Queue

A queue is a set of tasks performed in a first in first out manner. you can understand it with a simple example, you see a ticket counter queue. People standing in lines, a person who comes first buys the ticket first 

There are mainly two types of queues

1.1 Serial Queue

A serial Queue is a type of queue in which tasks are added first, executes first then after another task is going to execute. If a task a running, then all the other tasks are waiting for their execution. Serial queue guarantee that only one task runs at a given time period. GCD controls the execution timing. You won’t know the amount of time between one task ending and the next one beginning. A serial Queue is used where the order of execution matters.

Swift Serial Queue Process

1.2 Concurrent queue

A Concurrent Queue is a type of queue in which all the tasks start their execution at the same time. But we did not have any knowledge about how much time is needed to complete each task available in a queue. In this type of queue order to start the task is fixed but the order of completing the task is not fixed. Any task can be completed first.

You can understand it with a simple example in which a few runners are running in a race. All runners started to run after the whistle sounds, but we can’t know which runner completes the race first.

Swift Concurrent Queue Process

2: Syncronous Vs Asynchronous

A Synchronous function returns control to the caller when the task is fully completed. You can call a synchronous function by the syntax:

DispatchQueue.sync(execute: -)

Output:

An Asynchronous function returns control to the caller immediately. It did not wait till the task was complete. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function. You can call a synchronous function by the syntax:

Dispatch Queue.async(execute: -)

Output:

3: GCD provides mainly three types of Queues.

3.1: Main Queue: – 

The dispatch queue is associated with the main thread of the current process. Most priority tasks are executed here Task like user interface updation is done here. The syntex for the main queue is –

DispatchQueue.main

3.2: Global Queue: – 

Concurrent queues that run on background threads are shared by the whole system. There are a total of four such queues with different priorities called Quality of services (QoS) like userInitated, UserInteractive, default, Utility and Background.

 3.2.1: Quality Of Service: –  

Use quality-of-service classes to communicate the priority behind the work that your app performs. The system uses those priorities to determine the best way to execute your tasks given the available resources.  For example, the system gives higher priority to threads that contain user-interactive tasks to ensure that those tasks are executed quickly. Conversely, it gives lower priority to background tasks and may attempt to save power by executing them on more power-efficient CPU cores. The system determines how to execute your tasks dynamically based on system conditions and the tasks you schedule.

userInteractive

The quality-of-service class for user-interactive tasks, such as animations, event handling, or updating your app’s user interface. It represents tasks that must complete immediately in order to provide a nice user experience. Tasks are run on main thread. 

 

userInitiated:

Code Example of QoS:-

Delaying a Task

Sometimes we have to schedule a task after a fixed time period. For that type of task, we use the asyncAfter to delay a task for a time interval. Schedules a work item for execution at the specified time, and returns immediately.

Performing batch of operations

A dispatch group is used to perform a batch of operations as a single unit. You can perform operations like downloading multiple files, and calling multiple APIs when these groups of tasks are completed DispatchGroup sends notify you about the completion of all the tasks using DispatchGroup.notify function.

Conclusion

Finally we can say Grand central dispatch is the powerful api for multitasking with sync and async programming in iOS. I hope you will like this. 😊 🎉

Leave a Reply