Why You Should Care About Grand Central Dispatch

Anika Morris
5 min readJun 10, 2020

--

If you’re an iOS developer, you have likely used Grand Central Dispatch (GCD) at some point. Maybe you’ve read Apple’s documentation which states that GCD “execute[s] code concurrently on multicore hardware by submitting work to dispatch queues managed by the system.” But what in the heck does that actually mean? Well, in order to understand GCD, we have to first understand the problem that it solves.

Multithreading in iOS

What is a thread? The best description I found in researching this article came from pwnall on Stack Overflow. Here it is in full:

“A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.

Suppose you’re reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers.

If you have a roommate, and she’s using the same technique, she can take the book while you’re not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were.

Threads work in the same way. A CPU is giving you the illusion that it’s doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. Just like you can share a book with your friend, many tasks can share a CPU.

On a more technical level, an execution context (therefore a thread) consists of the values of the CPU’s registers.

Last: threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads.”

In iOS, processes and applications are executed on multiple threads. This could be the result of multiple cores or a single processor performing context switches (running one thread and then switching to run another thread). Having multiple threads, or multithreading, gives the processor access to many threads at the same time so that it can execute tasks concurrently.

Note: It is tempting to say that concurrent tasks execute at the same time, but it’s important to keep the real definition in mind:

“Two events are concurrent if we cannot tell by looking at the program which will happen first.” (Downey, 2005)

Importantly, it is up to the operating system scheduler, not the programmer, to determine if, when, and how to switch to another thread. This raises some significant issues when we want to set constraints on the order or manner in which tasks are executed, so iOS uses GCD to help us create and enforce those constraints.

How does GCD work?

GCD is built on threads and manages a shared thread pool, a collection of threads on which tasks can be performed. When you add tasks to dispatch queues, GCD executes them on a thread of its choosing and, importantly, in FIFO (first in, first out) order. There are three main queues in GCD:

Main Queue: Serial queue that runs on the main thread

Global Queues: Concurrent queues shared by the entire system. These queues come with four different priority levels. From highest priority to lowest, they are high, default, low, and background.

Custom Queues: Can be serial or concurrent and will end up in one of the global queues based on the Quality of Service (or QoS) property, rather than directly specifying the priority.

What does it mean for a queue to be serial or concurrent? Both guarantee that tasks start in the order that they were added. Serial queues can only run one task at a time, but you won’t know how much time passes between one task ending and the next beginning. The main queue is a serial queue, which means we can be sure that tasks in the main queue execute one at a time and in the same order that they were put in the queue. Concurrent queues can start one task and then also start the next task without the first one finishing. With a concurrent queue, we don’t have the ability to know the order in which tasks finish, the time in between them, even or the number of tasks running at any given time. And that’s okay! As programmers, we shouldn’t lend importance to those details. It’s our job to ensure that our code runs smoothly anyway. So what does that look like in practice?

Executing Tasks

Tasks can be executed either synchronously or asynchronously, which determines whether the function waits to return until the task is complete (synchronous), or returns immediately after being called regardless of the state of the task (asynchronous). They are submitted to a dispatch queue using DispatchQueue.sync(execute:) or DispatchQueue.async(execute:). For example:

Significantly, GCD dispatch queues themselves are thread safe, which means you can add tasks to a dispatch queue from any thread. This small guarantee is actually saving us a ton of headaches. It would take crazy amounts of extra time and effort to manually lock and unlock each thread and synchronize access to each queue. (If you are interested in what it takes to manage thread execution and the problems that can arise, I highly recommend the Little Book of Semaphores.) The ability to harness control over the order and manner in which tasks are executed is huge and has the potential to significantly increase the efficiency and performance of your iOS applications. Thank you, GCD!

Works Cited / Further Reading

Dekhayser, Evan. “Grand Central Dispatch Tutorial for Swift 4: Part 1/2.” Raywenderlich.com, 15 Aug. 2018, www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1–2#toc-anchor-005.

Dekhayser, Evan. “Grand Central Dispatch Tutorial for Swift 4: Part 2/2.” Raywenderlich.com, 15 Aug. 2018, www.raywenderlich.com/5371-grand-central-dispatch-tutorial-for-swift-4-part-2-2#toc-anchor-004.

Downey, Allen B. “The Little Book of Semaphores.” Green Tea Press, 2005, https://greenteapress.com/wp/semaphores.

Lewis, Gabriel. “Threading in Swift Simply Explained.” Medium, Better Programming, 2 July 2019, https://medium.com/better-programming/threading-in-swift-simply-explained-5c8dd680b9b2.

--

--