Multi-Threading

Q= What is multithreading?

Multithreading is the most important concept, every developer must know about them.

  • When we try to execute multiple tasks at the same time then our Ui get stuck and wait for another task to be completed.
  • Because our iPhone has only one CPU and it can perform only one operation at a time ie. once per clock cycle. But our CPU is so fast because it can perform millions of operations in 1 second.
  • So, we use multithreading in order to perform several tasks according to our need.
  • Multithreading allows the processor to create concurrent threads ( executed in parallel)then it can switch in between And as a Developer or smartphone user we are not able to see when it switches Because they occur so rapidly. It is also named as concurrency.
  • Example: when we open any app in iPhone then our UI works smoothly with animations along with download a file from the server then our download performs in the background and it doesn’t affect the app UI.
  • Real-life Example: in messaging apps, we send a large video to another person and along with we also watch a video with texting, This is possible because of multithreading.

Types: 

We can achieve this in 2 ways:

1.GCD

2. nsOperation.

Now, we focus on GCD

GCD ( Grand Central Dispatch ) GCD is an API provided by Apple to allow you to handle concurrent operations in a better way and prevents the app to freeze and gives a better experience to users.

In GCD there are 3 queues:-

1. Main: The main queue has the highest priority than others and it runs on the main thread.

Note: All the UI must update on this queue otherwise our app will be stuck.

 DispatchQueue.main.async {

                                // this is main thread , ui update must be done here

                                 }

2. Global: Global queue runs on background threads they are non FIFO means our tasks are started according to our need But their completion is not in their respective order.

This Queue is divided into 4 main types and a default type according to QOS(Quality of Service), from highest to lowest priority.

a. userInteractive: Work is complete in an instant and it is Similar to the main thread.

b. userInitiated: Work takes a few seconds or less to complete.

Priority =high

c. Default:-  priority is default

d. Utility: Work takes a few seconds to a few minutes To complete.

Priority=low

e. Background:- work takes more time such as minutes or hours

Priority=Background

Note: Utility and background queue are used for heavy tasks that need some time to complete.

DispatchQueue.global(qos: .background).async {

                                 // every heavy operation must be done here

                               }

3. Custom: we can create custom queues according to our need and give any QOS based on our needs.

let parellelQueue = DispatchQueue(label: “parellelQueue” , qos: .background, attributes:   

                               .concurrent)

We also need to understand what is Async and sync to understand multithreading:

-when we use GCD, we can use synchronously or asynchronously according to our needs for dispatch a task.

We use Async when we want to start another task and this another task can start without the completion of first.

We use sync when we don’t want to start another task until our first task is complete.

Example:

DispatchQueue.global(qos: .background).async {

                           for i in 0…4 {

                               print(“ How are you \(i)”)

                         }

                    }

           DispatchQueue.global(qos: .userInteractive).async {

                           for i in 0…4 {

                               print(“ I am fine \(i)”)

                         }

                   }

Output:

I am fine 0                         // userInteractive task

How are you 0                  // background task

I am fine 1                         // userInteractive task

How are you 1                  // background task

I am fine 2                         // userInteractive task

How are you 2                  // background task

I am fine 3                         // userInteractive task

I am fine 4                         // userInteractive task

How are you 3                   // background task

How are you 4                    //background task

Conclusion: Here, the priority of user interactive task is high therefore, it will be executed first and background task is completed at a different time as you have seen on output.

Coding Example: assume we want to download a big video and does not want to wait until the video is downloaded. So we use multithreading so that our downloading should take place in Background.

DispatchQueue.global(qos: .background).async {

      let bigVidio = downloadVidioFromServer()

           DispatchQueue.main.async {

                      // Any UI update

}

}

 

 

 

Leave a Reply