Grand Central Dispatch (GCD) part I

Ekramul Hoque
Good Morning Swift
Published in
10 min readMay 30, 2018

iOS monster GCD with Swift | Detail definition and Example

Photo:Internet

We all Know The Stupid computer can’t do more than one task at a time without concurrent programming or multiple CPU

Click here for sample app

Introduction :

Concurrency is huge topic in programming language and a bit low-Lavel. In this article I will discuss about Concurrent Programming. There are many APIs for concurrency.Apple release two low label API for concurrent programming NSOperation and Dispatch Queues.I will cover the Grand Canter Dispatch (GCD) and explore why we need it, how implement it With Swift .And hope you will be master on this API ..So let rock together ..

So why we need concurrency :

We all know computer (Single core) can’t do multitask at a time .But in computing multitask is mandatory.So for solving this issue concurrent concept invented .Concurrency is the way of doing multitask at a time.

In the heigh level : Consider we have an app which have two task at a time one is downloading data from Network and another is update UI.Both task need to execute at the same time .If downloading (Network request) need some time like 30 second in this time UI will be stop updating.And App will he freeze even can be crushed .From the user side its vary bad .No user will use this app again ..So how We can handle this ??. We need to concurrent programming..

so

Before we Dive Into Concurrency we need to recap some definition which will help us to batter understanding :

Task Can Execute Two way Serially or Concurrently

Serially: Task Can the Execute Serially one by one .One task start when its previous task finished Like FIFO(First In First Come ).

We can give an example like a cinema ticket counter. If there is one counter and all customer make a line. Its a Serial queue .When one customer bought ticket he will be out of the line and next customer will come for the ticket. Its a serial queue.

Ticket Counter Queue

Concurrency:

Concurrency is simply a concept of running Multiple Task at the same time .This Can be happen either in single core CPU or multi core CPU.In single Core CPU its happen by time-slicing .One thread run than perform a context switch than run another thread or multi core CPU execute multiple thread by parallelism.

Concurrency is two type :

1.Concurrent without parallelism

2.Concurrent with parallelism

Photo : raywenderlich

Thread :

Thread is the subunit of process in other word thread is the group of task which scheduled independently by the operating system scheduler.

Queue :

Queue is the data structure that manage object in the order first in first out (FIFO).In Our example cinema ticket customer line is queue .

Why do We Need Concurrency?

We Need concurrency for some very important reason :

Responsive UI Always : When any iOS apps launch first time its run a main queue by default .And main queue can update user interface .So we need to make this queue free for UI only and others heavy task in background queue .So here Concurrent programming need to manage this issue .

Utilise iOS Device : Now a day iOS Device is multicore processor and with concurrent programming we can use multicore processor with parallel.

Make Free to Main Queue

Grand Canter Dispatch (GCD):

So we already cover enough topic for the concurrent programming.Apple have two API for concurrent programming .NSOperation and GCD .Most common use is GCD(Grand Canter Dispatch).We can manage multi thread on iOS and MacOS by this API.ITs can manage synchronous and asynchronous queue of task .

GCD have dispatch queue for manage all queue one by one in FIFO order.GCD provide two type of queue and these are serial queue and concurrent queue .Both queue can run synchronously or asynchronously.We Will discuss it after some time .

Serial Queue:

Serial queues guarantee that only one task runs at any given time. GCD controls the execution timing. we wont know when task start and finised all manage by dispatch queue.

Here in this picture all task are running are serially one by one task 1 complete than tast 2 start thn task three start so on …

Concurrent Queue:

Concurrent queue run multiple task at time. all task are start by order thy are add but we don’t have knowledge when all are on will be finish or how many task doing at a time all are mange by system.

Here in picture task 1 start and this time no task are running with it but task 1 and Task 2 are start in same time but task 1 finished before task 2 .So it concurrent queue we don’t know when task will be finish or how much time will take bu we just know task will run by how we ordered it .

its Depend on Dispatch queue to multiple task will be run non different core or will happen by context switching .But usually if core are available than its happen on core otherwise use context switching.

GCD provides three main types of queues:

  1. Main queue: Its runs on the main thread and its a is a serial queue.All UI updated happen in this queue .
  2. Global queues: Its concurrent queue and its call also background queue its shared by total system and with this queue have six different queue based on task priority.

3.Custom queues: This queue Created by user (developer) its either be serial or concurrent.Its Good to not create custom queue instead of using apple default global queue

So Lets Start creating Queues :

Simplest way to create dispatch Queue like this :

let queue = DispatchQueue(label: “com.simpleQueue.Ekram”)

Here i create a custom queue with unique label .Its Good to name use reverse DNS notation Apple recommended it not mandatory .

LETS START CODE :

so now we just create the task and add to this queue its very simple . So Here i created a simple project and attached here in my github.This project is very simple i created function and i will write code in this function and than i will call it from viewDidAppear. Like this ..

Here in simpleQueue Function i create a dispatch queue called queue with the identifier “com.simpleQueeue” And we Add to queue With the synchronous method .We can added task by asynchronous too .We Will Discuss about it later . We add task using a for loop print simple string and a Love emoj.And if we add another for lop right before this block .Like this

Custom Serial queue :

Lets Explain Again :

  1. here we create a dispatch queue constant and give it a unique identifier
  2. we add task(first loop) to queue by sync method
  3. we add another for loop to body

So now lets see what happen in console :

In console its print the 10 times ‘’Custom Green Lover’’ and than print ‘’General lover ‘’ Because of first loop is sync method added to queue and its become blocked When its finished task than start second loop and print another ten times “general Love”.

  1. Here Queue is serial queue because we didn’t set it attribute as concurrent .if we don’t set it attribute than its default serial queue.
  2. sync method block execute complete than its return

3.If we don’t create any queue than its default is main queue .

Custom serial queue with async method:

Now if we change method sync to async than let see what happen

So here in console we see a interesting output. Because of we change sync to async .async method return before it task done .so main queue is now free so when async return main queue execute .So both queue execute parallel.my custom queue execute in background .

Its important to know that custom queue have a attribute for priority .Which queue will more important to system which will be execute first its more than important . Its necessary to tell now that main queue is always height priority queue and all UI element updated from this queue and its make apps responsive .on other GCD have a enum called Quality of Service which have all others six priority case .By this all six case we can fix which task will get which priority .I am summarising all case also called Qos Classes .Here listing first class is higher priority and last is lowest priority :

There are primarily 6 levels in Quality of Service(Qos)

(Task and duration description by Apple )

UserInteractive (highest Priority):Work that is interacting with the user, such as operating on the main thread, refreshing the user interface, or performing animations. If the work doesn’t happen quickly, the user interface may appear frozen. Focuses on responsiveness and performance

Duration of work: Work is virtually instantaneous.

UserInitiated:Work that the user has initiated and requires immediate results, such as opening a saved document or performing an action when the user clicks something in the user interface. The work is required in order to continue user interaction. Focuses on responsiveness and performance.

Duration of work:Work is nearly instantaneous, such as a few seconds or less.

Default:The priority level of this QoS falls between user-initiated and utility. This QoS is not intended to be used by developers to classify work. Work that has no QoS information assigned is treated as default, and the GCD global queue runs at this level.

Utility:Work that may take some time to complete and doesn’t require an immediate result, such as downloading or importing data. Utility tasks typically have a progress bar that is visible to the user. Focuses on providing a balance between responsiveness, performance, and energy efficiency.

Duration of work:Work takes a few seconds to a few minutes.

Background:Work that operates in the background and isn’t visible to the user, such as indexing, synchronising, and backups. Focuses on energy efficiency.

Duration of work:Work takes significant time, such as minutes or hours.

Unspecified (lowest ):This represents the absence of QoS information and cues the system that an environmental QoS should be inferred. Threads can have an unspecified QoS if they use legacy APIs that may opt the thread out of QoS.

Lets Code with Qos:

First in our simple apps we make new function called queusWithQosAtrribute()and call it from the viewDidAppear().

First create two queue like this

Notice here is new attribute called qos and we select userInitiated for both of them lets add task to them and see what happen !

So here is async method and thats why its not blocking execution another queues and both queue have same priority .So both queue execute one than start another .Nothing much to explain ..

No lets change one queueTwo Qos attribute to utility and lets see what output we get in console :

first Dispatch queue is execute faster than second queue cos utility Qos is lowest priority .So Second queue can run when first it running but it didn’t.Cos first queue is more higher priority(userInitiated) than second one.

So we are almost clear about priority but we will experiment one more .Change the first Qos to background :

This time second queue is run faster than first queue cos utility is higher priority than background.

Now lets experiment with Main queue add another lop to right before the second Queue .

So here is another example of main queue is most higher queue so its run fast than other two queue with parallel.

Concurrent Queue :

So here We can create custom concurrent queue by initialising concurrent as a parameter when we create Dispatch queue .Like This way ..

So before We learn how to create serial Queue and with Quality of service.But all happen serially .If we add more than one task in any serial queue than it will execute one after one based and based on sync or async method.If it is sync than task will complete than exit and return the method and if it is async than task will return before complete .At that time all queue got priority based on its Quality of service classes .Now we will examine concurrent queue first we create a serial queue called newQueue.And add Three loop with same Qos(Quality of services )Than see what happen :

Here is newQueue have three type of task all executed serially one after another .Nothing special .

Now lets select the attribute argument property as a Concurrent like this :

And add task to queue and see that happen :

So surpassingly three of queue are executing together its the magic of concurrency .All executing parallel ..and Qos also will be effect …

So Here We already cover a lot I will explain remain in next article. Thank you for staying with me Keep Rocking don’t forget to share and clap for my effort

Click Here For Part 2.

--

--