Dispatch queues: main, serial and concurrent
GCD gives you three kinds of queues:
| Queue | Runs tasks | Use for |
|---|---|---|
DispatchQueue.main | one at a time, on the main thread | every UI update |
DispatchQueue.global(qos:) | many at once, on background threads | slow work: decoding, image processing |
your own DispatchQueue(label:) | one at a time (serial), on a background thread | protecting shared data, ordered work |
You add work with async or sync:
asyncadds the closure to the queue and returns immediately. The caller keeps going.syncadds the closure and waits until it has run.
The everyday pattern is “background work, then back to main”:
DispatchQueue.global(qos: .userInitiated).async {
let image = ImageResizer.thumbnail(for: data) // slow, off the main thread
DispatchQueue.main.async {
self.imageView.image = image // UI only on main
}
}The QoS (quality of service) tells the system how urgent the work is, from .userInteractive and .userInitiated (the user is waiting) through .utility to .background (prefetching, cleanup).
Serial queues give mutual exclusion and ordering without locks; concurrent queues (global ones, or your own with attributes: .concurrent) run tasks in parallel on GCD’s thread pool. sync runs the block on the calling thread when possible, and sync onto a serial queue you’re already executing on (including main.sync from the main thread) deadlocks; libdispatch detects the simple case and crashes with “dispatch_sync called on queue already owned by current thread”. QoS propagates: async captures the submitter’s QoS, and a high-QoS sync onto a queue with lower-QoS work queued boosts it, which is how GCD mitigates priority inversion (it can’t help with semaphores, which have no owner). The pool grows when threads block, up to a limit of roughly 64 worker threads: blocking many tasks on a concurrent queue (synchronous network calls, semaphore.wait) causes thread explosion, with memory and context-switch costs and, once the limit is hit, deadlock-like stalls. Prefer few serial queues with target queues (a hierarchy funneling into one queue per subsystem) over many independent queues. Swift concurrency’s cooperative pool, limited to the number of cores, exists precisely to avoid thread explosion, which is why blocking inside async code is forbidden. Use the Main Thread Checker and Thread SanitizerThread SanitizerA runtime tool that reports data races, two threads accessing the same memory at once, during a debug or test run.Open in glossary → in debug schemes.
Predict the output
This runs in viewDidLoad (on the main thread). In what order are the lines printed?
print("1")
DispatchQueue.main.async {
print("2")
}
print("3")main.async adds the closure to the end of the main queue and returns at once. The main thread finishes what it's doing (printing 3 and the rest of viewDidLoad) before it gets to the queued closure, so 2 comes last. With main.sync instead, the app would deadlock: the main thread would wait for a closure that only the main thread can run.
final class ThumbnailCache {
private var storage: [URL: UIImage] = [:]
private let queue = DispatchQueue(label: "com.example.thumbnail-cache") // serial by default
func image(for url: URL) -> UIImage? {
queue.sync { storage[url] } // reads wait for earlier writes
}
func store(_ image: UIImage, for url: URL) {
queue.async { self.storage[url] = image } // writes don't block the caller
}
}A button that freezes the app forever
Tap the line with the bug.
@IBAction func saveTapped(_ sender: UIButton) {
saveButton.isEnabled = false
DispatchQueue.main.sync {
statusLabel.text = "Saving…"
}
DispatchQueue.global(qos: .userInitiated).async {
self.store.save(self.document)
DispatchQueue.main.async { self.saveButton.isEnabled = true }
}
}Hint: Which thread runs an @IBAction, and what does sync wait for?
Button actions run on the main thread. main.sync puts the closure on the main queue and waits for it to finish, but the main queue can’t run it until the current work (this very action) finishes. Each waits for the other, so the app freezes; GCD usually detects this case and crashes instead.
You’re already on the main thread, so just update the label directly:
@IBAction func saveTapped(_ sender: UIButton) {
saveButton.isEnabled = false
statusLabel.text = "Saving…"
DispatchQueue.global(qos: .userInitiated).async {
self.store.save(self.document)
DispatchQueue.main.async { self.saveButton.isEnabled = true }
}
}Rule of thumb: never call sync on the queue you might already be on, and never call main.sync at all unless you’re certain you’re on a background thread.
Reader-writer with a barrier
A concurrent queue plus .barrier writes allows parallel reads and exclusive writes: the barrier block waits until running reads finish and holds back later ones until it’s done. Barriers only work on queues you create; on a global queue .barrier is ignored and the block runs like any other. In new code an actor gives the same safety with compile-time checking, and OSAllocatedUnfairLock (iOS 16) or Mutex (iOS 18, Swift 6) is cheaper for tiny critical sections.
private let queue = DispatchQueue(label: "com.example.settings", attributes: .concurrent)
func value(for key: String) -> String? { queue.sync { storage[key] } }
func set(_ value: String, for key: String) {
queue.async(flags: .barrier) { self.storage[key] = value }
}Deep diveWhy thread explosion happens and how Swift concurrency avoids itInterview favorite
When a task on a concurrent queue blocks (waiting on a lock, a semaphore or a synchronous network call), GCD sees a core going idle and starts another thread so other work can proceed. Submit 200 such tasks and you get dozens of threads, each with its own stack (512 KB by default for secondary threads), all competing for a few cores. When GCD’s thread limit is reached, new work waits for threads that are themselves waiting, and the app stalls.
Swift concurrency’s executor uses one thread per core and never adds threads when one blocks. That’s efficient only if tasks don’t block: an await gives the thread back, while semaphore.wait() or Thread.sleep inside a task holds one of a handful of threads. That’s why mixing semaphores with async code can hang the whole app, and why Apple’s guidance is to keep blocking calls out of tasks.
- Main for UI, global by QoS for parallel work, private serial queues (with target queues) for state;
asyncreturns,syncwaits. synconto the current serial queue (includingmain.syncfrom main) deadlocks.- QoS propagates and resolves priority inversion for queues, not semaphores. Blocking on concurrent queues → thread explosion (~64 thread limit); Swift concurrency’s pool forbids blocking.
- Barriers only on custom concurrent queues; prefer actors or
Mutex/OSAllocatedUnfairLockin new code.
Check this part
What does DispatchQueue.main.async { … } do when called from the main thread?
Where must you set imageView.image after resizing a photo in the background?
What is thread explosion in GCD?
What happens with async(flags: .barrier) on DispatchQueue.global()?