MultiThreading in iOS

MultiThreading – Multithreading means multiple tasks at the same time and the tasks which are being executed on what are Threads.

Or we can say –

  • In our app when we try to execute multiple tasks at the same time then our app UI will freeze because our mobile-only has 1 CPU.
  • So we can use Multithreading to perform various tasks at the same time.
  • Taking advantage of this power is important. There are several options to manage that complexity. Grand Central Dispatch is one of them.

Types of Thread

  • Thread where the user interacts with your apps like button click and scrolling table i.e known as Main Thread.

  • The above image explains that if we do all these things on the Main Thread (i.e download image or API’s hit) then our application will freeze and that makes the user experience horrible.
  • To enhance the user experience we need to know about the Background Threads.
  • Thread on which we call API’s and download images from the server that thread is known as Background Thread.

  • To improve the user experience we need to do all heavy lifting (download image or API’s hit) on the Background Thread.

Grand Central Dispatch (GCD) – GCD is just an API built on top of the thread and handles all our heavy lifting tasks and creating and managing all our threads.

  • With the help of GCD, we execute all the heavy tasks in the background and prevent our application UI from freezing.

Dispatch Queues – As clear with their name dispatch queues means to dispatch the queues from background thread to the main thread or vice versa.

  • All dispatch queues adopt FIFO data structure i.e First In First Out.
  • Queues can be either serial or concurrent.

Types of Queues – GCD has 3 main types of queues:

Serial Queues

  • Serial queues execute the task one after the other.
  • Serial queues begin the other task when the one task is 100% completed.
  • To execute the task in serial wise we need to use Serial Queuesalways, because the order of the tasks execution matters in Serial Queues.

Concurrent Queues

  • In Concurrent Queues, all tasks are triggered at the same time.
  • Serial of the task doesn’t matter in Concurrent Queues, because the execution of the orders is unpredictable in this queue.

  • In the above image Task, 1 doesn’t have to wait for Task 0 to complete because there’s no waiting and all tasks run at the same time.

Custom Queues –

  • Custom queues are queues which we can create on your own with our requirement.
  • Custom queues can be Serializedor Concurrent.

Synchronous vs. Asynchronous

With GCD you can dispatch a task either synchronous or asynchronous.

Synchronous – means users can do only one task at a time. We schedule a block of work synchronously by calling –

Asynchronous – means users can do multiple tasks at the same time. He is free to do other activities at the same time. We schedule a block of work asynchronously by calling –

 

Leave a Reply