Concurrency in iOS - 1: Introduction to Grand Central Dispatch and Operations

In this blog series, I will try to simplify the concept of Concurrency in iOS using the Swift programming language. I myself have struggled with it for a long period of time and in the recent past started putting more effort into understanding it and implemented it certain apps successfully. 

This whole series will evolve both as tutorial series with explanations of various important concepts with practical examples and a cookbook kind of recipes that you can pick up quickly in your iOS projects.

Hope you find the series useful and without wasting any time lets get some concepts cleared out of the way.

In iOS development ecosystem, there are majorly 2 ways to handle threads. 


1. Grand Central Dispatch: For one time tasks we do not need to manage the state.

2. Operations: For reusable tasks that need to be performed multiple times.

Grand Central Dispatch (referred as GCD)

  • GCD is the implementation of C's libdispatch library which is used to queue up tasks and run them in parallel. 
  • It uses thread under its implementation which abstracts the complications from developers.
  • It uses a queue to manage the execution of tasks.
  • Tasks are prioritized in FIFO (First In First Out) manner.
  • Whenever a task is submitted it picks up threads that are available in the system.
  • To make apps perform better and be responsive all the time we try to make any long non UI related tasks run in the background.
Queues in GCD can be created either are Serial or Concurrent.

Serial: Serial queues have only one thread associated to them which means they can run only a single task at a time.

Concurrent: Concurrent queues can have 1 or more threads associated to them which allows them to run multiple tasks submitted to it if the system resources allow.

Asynchronous DOES NOT mean it is also Concurrent. It just means that it will not block the UI when executing.

Operations

  • GCD is for one time tasks only.
  • Operations are for tasks that require a reusable functionality for example Image Processing.
  • Operations are created by Subclassing the Operation class.
  • Operations are submitted to OperationQueues for execution.
  • As Operations are full-fledged classes, that means they can contain variables that can tell us about the state of the task.
  • There are major 4 states that Operations hold:
    • isReady
    • isExecuting
    • isCancelled
    • isFinished
  • We should never run Operations directly because they are sync by default, this is where the role of OperationQueues come into play.

Comments

Popular posts from this blog

What happened to the blog ?

Why I love to be a programmer ?