CloseHomeAboutBlogCourse
Bob I’m an iOS instructor/blogger from S.Korea.July 14 • 5 min read • Edit

Intro to Grand Central Dispatch in Swift with Bob

Threading? Concurrency? Dispatch Queue?

Motivation

My #1 follower, The Bao, said

“I suggested a topic about MultiThreading supporting functions, namely Dispatch Semaphore, DispatchGroup, Flags, Options parameter when creating a Queue and how to do async tasks. I have learned it and saw some tutorial but these do not explain good enough about advanced GCD.” — Nov 26, 2016

I was like, “Shit, that’s a lot of stuff to cover” 😅

Audience

I won’t cover much of what he asked. However, I will cover the fundamental first. I assume you’ve heard Grand Central Dispatch (GCD) is a library built by smart Apple engineers so that we don’t need to worry about handling memory while executing multiple functions at the same time.

The Why

Let’s first talk about why GCD exists in the first place. Imagine you are an iOS developer at Snapchat. The app needs to download upcoming images and videos from the server(database) while a user flips through a hot cheek’s story. How?

Absolute no idea.

“Theoretically”, to achieve the effect, you’d have to create two or more threads (groups of task done by CPU). The first part deals with flipping the image. The second networking with the server.

Do I know how? Nope. 👏

Here comes our savior, Grand Central Dispatch. If I were to explain the concept to a 6-year old, GCD gives you (iPhone) the ability to text your friend (main) while taking a poop (background) with a couple lines of code.

GCD is a magic. It’s like pressing a couple of buttons on a microwave and the food starts heating up. You could study the ins and outs, but you don’t have to. Remember, there are 100+ frameworks by Apple alone.

DispatchQueue

Don’t freak out. DispatchQueue is just an ugly and “sound smart” class name.

The DispatchQueue class is like a manager for constructor workers.👷 The manager can assign heavy work (UI updating) to a dude who benches 350 pounds 🏋🏾 and assigns light work (networking) to a guy who weighs 97 pounds.

Every iPhone has two pre-existing construction workers. Most of the time, if you don’t specifically mention you need more help, you never use the lightweight. Everything is done by the heavy dude.

If you’ve never used GCD, then the heavy dude has been creating those UIs and tables for you. 💪 Of course, the lightweight has been taking care of the system related task pertaining to iOS.

The code below tells how to access your main (heavy) and background (lightweight) objects (workers).

let main = DispatchQueue.main

let background = DispatchQueue.global()

However, if the manager needs to get another 97 pounds, he could simply create an object (lightweight) as shown below.

let helper = DispatchQueue(label: "construction_worker_3")

Since we have access to those objects, now it’s time to use their muscle by assigning some work from us, geeks 😎

Sync vs Async

Before I talk about the difference between the synchronous and asynchronous execution, let’s run the code block first.

Excuse me for its format. I tried to have it as concise as possible.

func doSyncWork() {
  background.sync { for _ in 1...3 { print(“Light”) } }
  for _ in 1...3 { print(“Heavy”) } } // main

  doSyncWork()
  // Light
  // Light
  // Light
  // Heavy
  // Heavy
  // Heavy

If the light dude (background) runs the block synchronously, then it prevents any dudes from running at the same time until the code block is finished. It’s a bottleneck.

func doAsyncWork() {
 background.async { for _ in 1...3 { print(“Light”) } }
 for _ in 1...3 { print(“Heavy”) } }                // main
doAsyncWork()
// Light
// Heavy
// Heavy
// Light
// Heavy
// Light

If the background queue (an iOS term for a construction worker) runs the block asynchronously, it runs at the same time with the main queue.

At Snapchat, if you use the background queue to network synchronously, the UI will be frozen like 99% of the time. And, you will be fired.

Interestingly though, the main queue and the background queue do the job at the same time. Now, let’s create our own custom construction workers.

let asianWorker = DispatchQueue(label: "construction_worker_1")

let brownWorker = DispatchQueue(label: "construction_worker_2")

func doLightWork() {
  asianWorker.async { for _ in 1...10 { print("👷") } }

  brownWorker.async { for _ in 1...10 { print("👷🏽") } } }

  doLightWork()
  // 👷, 👷🏽, 👷, 👷🏽, 👷, 👷🏽, 👷, 👷🏽, 👷...

We’ve created two extra queues which possibly can be used for anything such as downloading and uploading pictures and including doing nothing but chilling. 👍

Prioritization

Even if you create those queues (workers), you may want to decide which task has a great importance for an execution. For example,

let whiteWorker = DispatchQueue(label: "construction_worker_3", qos: .background) // lower importance

let blackWorker = DispatchQueue(label: "construction_worker_4", qos: .userInitiated) // higher importance

func doLightWorks() {
 whiteWorker.async { for _ in 1...10 { print("👷🏻") } }
 blackWorker.async { for _ in 1...10 { print("👷🏾") } } }

doLightWorks() // 👷🏾, 👷🏻, 👷🏾, 👷🏻, 👷🏾, 👷🏾, 👷🏻, 👷🏾, 👷🏾, 👷🏾, 👷🏻, 👷🏾,👷🏾, 👷🏾, 👷🏻, 👷🏻, 👷🏻, 👷🏻, 👷🏻, 👷🏻

blackWorker, whose qos is .userInitiated did more work in the beginning and than whiteWorker, whose qos is .background. qos stands for “Quality of Service” Why? I have no idea. It’s just a fugly name.

There are primarily 6 levels in Quality of Service

  1. userInteractive (highest Priority)
  2. userInitiated
  3. default
  4. utility
  5. background
  6. unspecified (lowest )

Last Remark

I primarily used the construction worker vs manager relationship to describe how GCD works. ❤️ for the creativity? If you like it, make sure share with your community. Part 2 is ready now, here. You will learn how to use GCD for updating UIs while networking like a boss.

In this article, I’ve used trailing closures to execute blocks of code that comes after async . It has to do with closures. If you wish to learn more about intro to functional programming and keywords such as @escape and @autoclosure, feel free to check out my Swift intermediate course.

About Me

iOS Developer from South Korea. Feel free to follow my story on Instagram or get serious on LinkedIn