iOS Concurrency and Threading

Grand Central Dispatch provides language features to support concurrency on iOS. It works with Dispacth Queue (objects) in our application.

By default, every iOS application has

  • 1 x Main Thread (Serial Queue)
  • 4 x Background Thread (Concurrent Queue)

Main thread is reserved for UI related tasks. And, we are able to create more custom (concurrent or serial) threads. Concurrent and serial queues help us to manage how we execute tasks.

Serial Queue:

Executes tasks one at a time.So, task 2 will not start until 100% of task 1 completed.

  • Slower
  • Predictable execution order
  • Prevents race conditions

Concurrent Queue:

Every task starts at same time. Does not wait for a task to finish before starting the next one.

  • Faster
  • Unpredictable order of completion

In consequence of any DispacthQueue task can be run synchronously or asynchronously (actually those are a separate concept), there are 4 case to be considered.

Case 1: Concurrent queue + Executing asynchronously;

The control returns immediately to the caller. May execute other tasks in parallel to the currently submitted one.

Case 2: Concurrent queue + Executing synchronously;

The caller waits until the task completes. May execute other tasks.

Case 3: Serial queue + Executing asynchronously;

The control returns immediately to the caller. Current task is the only one running on the queue.

Case 4: Serial queue + Executing synchronously;

The caller waits until the task completes. Current task is the only one running on the queue.

  • Submitting tasks synchronously through the main queue, causes a deadlock. (That's true for any serial queue)

Software engineer @huawei , musician

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store