With GCD, how do serial and concurrent DispatchQueues differ, and why must a star-chart screen's UI update go back to DispatchQueue.main?
answer
- one at a time versus side by side
- DispatchQueue(label:attributes: .concurrent)
- global(qos:) is concurrent, main is serial
- UIKit belongs to the main thread
- async returns at once, sync waits
basics
~20 sA serial DispatchQueue runs one work item at a time, in order; a concurrent queue starts items in order but can run several at once. DispatchQueue.main is a serial queue tied to the main thread, where all UIKit and SwiftUI updates belong.
solid answer
~40 sA **serial** queue, such as `DispatchQueue(label:)` with no attributes or `DispatchQueue.main`, runs one work item at a time in FIFO order, so its items never overlap. A **concurrent** queue, such as `DispatchQueue(label:attributes: .concurrent)` or a global queue from `DispatchQueue.global(qos:)`, starts items in FIFO order but lets several run at once on threads the system manages, so they can finish in any order. Apart from the main queue, GCD makes no promise about which thread runs an item. UIKit and SwiftUI must be updated on the main thread, so the screen reads and decodes the chart on `global(qos: .userInitiated)` and hands the image back with `DispatchQueue.main.async { ... }`. `async` returns at once; `sync` blocks the caller until the item has finished.
code
swift · 18 linesimport UIKit
final class StarChartViewController: UIViewController {
let chartView = UIImageView()
func showChart(from fileURL: URL) {
DispatchQueue.global(qos: .userInitiated).async {
// Slow file read and decode, off the main thread.
guard let data = try? Data(contentsOf: fileURL),
let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
// UIKit is touched only on the main queue.
self.chartView.image = image
}
}
}
}go deeper
Recall the two queue kinds, that DispatchQueue.main is serial and bound to the main thread, and the pattern of global(qos:).async for slow work followed by DispatchQueue.main.async for the UI update.
Explain that a concurrent queue starts items in FIFO order but finishes them in any order, that only the main queue promises a thread, and that sync blocks the caller while async returns at once.
Show judgment about queue count and quality of service: reuse global queues or target them instead of creating many private concurrent queues, pick userInitiated for work the user waits on, and keep blocking calls off the main queue.
Weigh a queue per subsystem against a few shared queues for debuggability and thread use, and decide when new UI-facing code should stop adding GCD hops in favour of main-actor isolation.
## What a dispatch queue is **Grand Central Dispatch (GCD)**, the libdispatch library, lets you hand closures, called **work items**, to **dispatch queues** instead of managing threads yourself. Apple's documentation describes a `DispatchQueue` as a FIFO queue: work items leave it in the order you submitted them, and the system runs them on a pool of threads it manages. Except for the queue that represents the main thread, the system makes no guarantee about which thread runs a given item. Queues come in two kinds: - **Serial queue**: runs exactly one work item at a time. The next item starts only when the previous one has finished. `DispatchQueue(label: "com.example.tiles")` with no attributes creates one. - **Concurrent queue**: starts work items in FIFO order but lets several run at the same time, so they may finish in any order. `DispatchQueue(label: "com.example.tiles", attributes: .concurrent)` creates one, and the **global queues** returned by `DispatchQueue.global(qos:)` are concurrent queues the system shares across the app. The `label` is a reverse-DNS string that shows up in Instruments and crash reports, so give every queue you create a meaningful one. ## Where the main queue fits `DispatchQueue.main` is a **serial** queue bound to the app's **main thread**. Its items run only on that thread, one at a time, between the events the run loop processes. UIKit and SwiftUI expect every view update on the main thread, so the main queue is where results go when they need to appear on screen. Long work does not belong there. Apple's documentation for `DispatchQueue.main` warns that a main thread left unresponsive for too long can end in a `0x8badf00d` watchdog termination, and recommends running long tasks such as network calls on a global queue or another background queue. ## The round trip for a star chart A star-chart screen that reads and decodes a large chart image follows three steps: 1. Submit the slow part to a global queue with a quality of service that matches the user's wait: `DispatchQueue.global(qos: .userInitiated).async { ... }`. 2. Inside that block, read the file and decode the image. No UI is touched here. 3. Hop back with `DispatchQueue.main.async { self.chartView.image = image }`, so the UIKit update runs on the main thread. Objective-C code in the same app reaches the very same queues through the C API, for example `dispatch_async(dispatch_get_main_queue(), ^{ ... })`, so Swift and Objective-C work items on the main queue are serialised together. ## sync versus async | Call | What the caller does | Typical use | |---|---|---| | `queue.async { }` | returns at once; the item runs later | starting background work, hopping to the main queue | | `queue.sync { }` | blocks until the item has finished, then returns its result | reading a value guarded by a private queue | `sync` does not move the caller anywhere: it waits. As an optimisation libdispatch often runs a `sync` item on the calling thread itself, except when the target is the main queue. Calling `sync` on a queue you are already running on deadlocks, which is why `async` is the default choice. ## Picking a quality of service `DispatchQoS.QoSClass` tells the system how important the work is: - `.userInteractive`: animations and event handling, the highest class. - `.userInitiated`: results the user is waiting for right now, such as opening a chart. - `.default`: the class used when nothing more specific is given. - `.utility`: long-running work whose progress the user does not follow closely, such as prefetching tiles. - `.background`: maintenance and clean-up the user does not see. Higher classes run sooner and use more energy, so marking everything `.userInteractive` costs battery and helps nothing. ## Mistakes that show up in review - Updating a `UILabel` or `UIImageView` from a global queue: it may appear to work and then corrupt or crash under load. - Assuming a concurrent queue finishes items in submission order: it only starts them in order. - Creating a new private concurrent queue per screen: Apple's documentation notes that each queue consumes thread resources and suggests the global queues instead. - Using `sync` to "make it run now": it only blocks the caller. - Doing network or disk work directly in a button handler: the main queue cannot process touches or redraw the screen until that work returns, so the app feels frozen. ## Ordering without extra threads When a piece of work must stay in order, for example writing chart files to disk one at a time, create a serial queue with `DispatchQueue(label:qos:attributes:autoreleaseFrequency:target:)` and pass a global queue as `target`. Apple's documentation recommends this: the queue keeps its one-at-a-time behaviour, while its items run on threads the global queue already manages instead of adding another source of thread creation.
- Does a serial queue always run its work items on the same thread?No. Apart from the main queue, GCD makes no promise about which thread runs an item; Apple's `DispatchQueue` documentation says so explicitly. A serial queue guarantees that its items run one at a time and in order, not that they share a thread. So never keep per-thread state for a serial queue's items, and check the queue rather than the thread when you need an assertion.
- How does Objective-C code in the same app send work to the main queue?Through the C API that the Swift overlay wraps: `dispatch_async(dispatch_get_main_queue(), ^{ ... })` submits a block to the same main queue that `DispatchQueue.main.async` uses, so Swift and Objective-C items are serialised together. Background work uses `dispatch_get_global_queue` with a class such as `QOS_CLASS_USER_INITIATED`.
- Why not create a new concurrent queue for every screen that does background work?Apple's documentation warns that each concurrent queue consumes thread resources, so many private concurrent queues push the app toward excessive thread creation. Submit concurrent work to a global queue, and when you need ordering, create a serial queue and set its target to a global queue, so it keeps its serial behaviour without adding another source of threads.
A serial queue is a single checkout lane: customers are served one at a time, in arrival order. A concurrent queue is a bank of lanes fed from one line: people leave the line in order, but several are served at once and may finish in any order.
- A concurrent queue finishes its work items in the order they were submitted.
- DispatchQueue.global() is serial, so its work items never overlap.
- Updating a UILabel from a background queue is fine if it usually works.
- A serial queue always runs its work items on one dedicated thread.
- Calling sync instead of async makes the work run on another thread sooner.