Member-only story
The Complete Guide to Concurrency and Multithreading in iOS
Main thread vs. background thread. Async/await and Actor. GCD vs. OperationQueue. Group dispatch, how to empower background thread, and more
Introduction
In this article, we will learn the following:
TABLE OF CONTENTSWhat Is Multithreading
Serial Queue vs. Concurrent Queue
Parallelism
Concurrency
Basics of Multithreading
Main Thread (UI Thread) vs. Background Thread (Global Thread)
GCD (Grand Central Dispatch)
DispatchGroup
DispatchSemaphore
DispatchWorkItem
Dispatch Barrier
AsyncAfter
(NS)Operation and (NS)OperationQueue
DispatchSource (How To Handle Files and Folders)
Deadlock (Issue What To Avoid)
Main Thread Checker (How To Detect Thread Issues)
Threads in Xcode (How To Debug Threads)
Async / Await / Actor Is iOS13+
I know there are lots of topics. If something is already familiar to you, skip it and read the unknown parts. There are tricks and tips.
Multithreading in Real-World Examples
Imagine you have a restaurant. The waiter is gathering the orders. The kitchen is preparing the food, the bartender is making the coffee and the cocktails.
At some point, lots of people will order coffee and food. That needs more time to get prepared. Suddenly the bell rings that 5x food is ready and 4x coffees. The waiter will need to serve the tables one by one even if all the products are prepared. This is the Serial Queue. With a serial queue, you are limited to only one waiter.
Now imagine there are two or three waiters. They can serve the tables much faster at the same time. This is Parallelism. Using multiple CPUs for operating multiple processes.
Now imagine one waiter will not serve one table at once, but will first serve all the coffees to all tables. Then, they will ask for the orders for some of the new tables, then serve all the food. This concept is called Concurrency. It is context switching, managing, and running many computations at the same time. It doesn’t necessarily mean they’ll ever both be running at the same instant. For example, multitasking on a…