DispatchQueue patterns for multithreading in iOS apps
Every screen in an iOS app juggles at least three kinds of work: parsing JSON, writing to disk, and painting pixels. Grand Central Dispatch exists to keep those jobs from blocking one another, and DispatchQueue is the handle you use to hand work off. A queue is not a thread — it is an ordered list of blocks waiting for a thread to run them — and that single distinction explains most of the bugs beginners hit the first time they reach for multithreading.
I write Swift from Atyrau in Kazakhstan, and most tutorials treat concurrency as something you configure once in a project settings panel. In practice you configure it every time you touch a network call. What follows walks through queue types, quality-of-service priorities and synchronisation helpers, with examples aimed at the kind of apps Australians actually download: banking apps from ANZ and CBA, supermarket specials from Woolworths and Coles, and health records that must stay responsive when a phone loses signal in a tunnel between Melbourne and Geelong.
What a DispatchQueue really is
Under the hood, libdispatch maintains a pool of worker threads that grow and shrink according to demand. When you create a queue you are not creating a thread; you are creating an ordering guarantee. A serial queue runs exactly one block at a time, in the order you submitted them. A concurrent queue may run several blocks at once, but blocks submitted to a single serial queue still execute in FIFO order, which is what makes queues the natural tool for protecting shared mutable state.
let serial = DispatchQueue(label: "com.example.serial")
let concurrent = DispatchQueue(label: "com.example.concurrent",
attributes: .concurrent)
The difference between dispatch_async and dispatch_sync is whether the caller blocks. dispatch_async returns immediately and the block runs later on a worker thread. dispatch_sync waits for the block to finish, which is why it feels fast on the main queue and catastrophic everywhere else. The classic deadlock is calling dispatch_sync on the main queue from a background thread: the background thread waits for the main thread, the main thread waits for the background thread, and the app freezes with no crash and no useful log line.
Serial queues and the main queue
The main queue is a special serial queue whose blocks run on the main thread, so any UIKit work belongs there. Everything else — decoding responses, hashing files, resizing images — should happen on a queue you create yourself. A custom serial queue is a simple, readable way to serialise access to a value that several blocks want to mutate, and it removes the need for locks in most small apps.
final class Counter {
private let queue = DispatchQueue(label: "com.example.counter")
private var value = 0
func increment() {
queue.async {
self.value += 1
DispatchQueue.main.async {
self.label.text = "Items: \(self.value)"
}
}
}
}
Notice the hand-off back to the main queue. A background queue finishing work does not update the screen; you have to cross the boundary explicitly, and forgetting that hop is the single most common UI bug in DispatchQueue code. If your project is on Swift concurrency already, @MainActor and await express the same boundary more compactly, but plenty of production UIKit code still uses queues, and Xcode's memory graph tooling still expects you to understand them.
Concurrent queues and quality of service
For genuinely independent work, use a concurrent queue. The global concurrent queues come with quality-of-service priorities that tell the scheduler how urgent a block is: .userInitiated for something a person is waiting on, .default for ordinary work, .utility for long-running but useful background tasks, and .background for deferrable work such as pre-fetching tiles. Getting the priority wrong hurts real users. A spinner that renders after a .background task is deprioritised feels broken, especially on the congested mobile networks Australians rely on outside the metro areas of Sydney, Melbourne, Brisbane and Perth.
Priority inversion is the other trap. If a high-priority block waits on a low-priority block to finish, the scheduler cannot run the high-priority work until the low-priority work releases the thread, so a photo upload tagged .background can stall the tap handler that was meant to feel instant. Keep user-visible work at .userInitiated or above, and resist the urge to spawn hundreds of concurrent tasks. Each concurrent block occupies a pool thread while it runs, so thousands of simultaneous tasks cause thread explosion, excessive memory pressure and sluggish frame rates on older devices that still make up a meaningful slice of the Australian market.
Groups, semaphores and cancellable work items
DispatchGroup is how you fan out and then wait for the results without blocking a thread by hand. You call dispatch_group_enter before starting each block, dispatch_group_leave when it finishes, and dispatch_group_notify to run a completion block once the count reaches zero. For an Australian health or banking app, that means hitting three endpoints at once — say, the My Health Record summary, a store locator and an eligibility check — then rendering them together.
let group = DispatchGroup()
var results: [String] = []
for endpoint in endpoints {
group.enter()
queue.async {
let data = try? Data(contentsOf: endpoint)
results.append(data?.base64EncodedString() ?? "")
group.leave()
}
}
group.notify(queue: .main) {
self.apply(results)
}
If you need to cap how many tasks run at once, a DispatchSemaphore limits concurrency: wait before starting, signal after finishing. Never wait on the main thread; the semaphore blocks that thread and you lose the UI entirely. If you have worked with backend systems you will recognise the shape — that NetBeans ActiveMQ walkthrough shows a message-driven bean consuming from a queue so the request thread stays free, which is precisely what a background DispatchQueue does for your interface.
Cancellability comes from DispatchWorkItem. Keep a reference to the work item, call cancel() when the view disappears or the user changes selection, and check isCancelled inside long loops. Barriers are the related trick: submitting a barrier block to a concurrent queue guarantees it runs after all previously submitted blocks and blocks new ones, giving you a reader-writer lock without writing a lock.
let cache = DispatchQueue(label: "com.example.cache", attributes: .concurrent)
let item = DispatchWorkItem { cache.async { self.rebuildIndex() } }
cache.async(execute: item)
Patterns worth adopting in your codebase
A few habits cover most of what juniors need, and they scale well beyond a single view controller:
- Keep every UIKit call on the main queue and return there explicitly after background work finishes.
- Prefer
dispatch_asyncoverdispatch_sync; reserve synchronous submission for cases where you genuinely need the result inline. - Use
DispatchGroupto join parallel work, andDispatchSemaphoreto keep fan-out within a sane limit. - Model cancellable work with
DispatchWorkIteminstead of scattering boolean flags through your view controllers. - Match quality-of-service priorities to user expectation, and measure with Instruments' Time Profiler before optimising.
Building your next parallel pipeline
Putting these ideas together, a realistic feature is a media grid: download a dozen images, decode them off the main thread, assemble a thumbnail grid on a serial queue, then hand the finished image to the main queue for display. Australian users will feel the difference on an NBN connection or a 5G phone in a crowded stadium, where the bottleneck is rarely CPU and often the scheduler. Scheduling also has a local wrinkle worth remembering: Sydney sits on UTC+10 and swings to UTC+11 for daylight saving, so any dispatch_after deadline you compute from a server timestamp needs the client's current offset, not a hard-coded one.
Open a new Xcode project today, add a DispatchGroup that downloads twelve images with a semaphore capping concurrency at four, and commit the assembled grid to the main queue — then profile it with Instruments before and after.