With GCD's DispatchGroup, how do you download several star-chart tiles in parallel and draw the constellation only after every download has finished?
answer
- count the outstanding work
- enter() before each request starts
- leave() exactly once per enter()
- notify(queue:) versus wait()
- async(group:) tracks only the block itself
basics
~20 sCall enter() on a DispatchGroup before each tile request, call leave() exactly once when that request completes, and register notify(queue: .main) to draw. The notify block runs once the count reaches zero, without blocking any thread.
solid answer
~40 sCreate one `DispatchGroup`. Before starting each download call `group.enter()`, and in that download's completion call `group.leave()` exactly once, on success and failure alike. Then call `group.notify(queue: .main) { draw() }`: GCD submits that block to the main queue when the count of outstanding work reaches zero, and nothing waits in the meantime. `group.wait()` reaches the same point by blocking the calling thread, so it never belongs on the main thread. Use `enter()` and `leave()` rather than `async(group:)` here, because `async(group:)` only tracks the block it submits, and a network call inside that block returns before its callback fires. Store each tile result on one queue, such as the main queue, so the parallel callbacks do not race on the dictionary.
code
swift · 26 linesimport Foundation
func fetchTile(named name: String, completion: @escaping @Sendable (Data?) -> Void) {
DispatchQueue.global(qos: .utility).async { completion(Data(name.utf8)) }
}
@MainActor
final class ConstellationLoader {
private(set) var tiles: [String: Data] = [:]
func load(_ names: [String], draw: @escaping @MainActor () -> Void) {
let group = DispatchGroup()
for name in names {
group.enter()
fetchTile(named: name) { data in
DispatchQueue.main.async {
self.tiles[name] = data // results land on the main queue
group.leave() // exactly once, on every path
}
}
}
group.notify(queue: .main) {
draw() // runs once, after the last leave()
}
}
}go deeper
Recall the three calls, enter, leave and notify, and that every enter needs exactly one matching leave.
Explain why enter and leave are needed for callback-based work instead of async(group:), why notify is preferred over wait, and how the results are stored without a race.
Diagnose the production failures: a missing leave on an error path that stalls the screen, a double callback that crashes, notify registered too early, and wait on the main thread tripping the watchdog.
Decide where fan-out code stays on DispatchGroup and where new code should use a task group, and set a review rule that every enter has a leave on every path.
## What a DispatchGroup counts A `DispatchGroup` is a counter of outstanding work that you monitor as one unit. Apple's documentation describes it as a way to attach several work items, possibly on different queues, and run a completion handler when all of them have finished, or to wait synchronously for them. The group has three operations: - `enter()` increments the count of outstanding tasks. - `leave()` decrements it. Apple's documentation says it must balance a call to `enter()` and that calling it more times than `enter()` is invalid, because the count would go negative; in practice libdispatch stops the app when that happens. - `notify(queue:execute:)` schedules a block on a queue for the moment the count reaches zero. `wait()` and `wait(timeout:)` block the calling thread until then. ## Wiring the tile downloads For a stargazing app that fetches the tiles of a constellation in parallel: 1. Create one `DispatchGroup` for this load. 2. For each tile, call `group.enter()` **before** starting the request. 3. In the request's completion, store the tile and call `group.leave()` **exactly once**, on every path, including errors. A `defer { group.leave() }` at the top of the completion makes that hard to break. 4. After the loop, call `group.notify(queue: .main) { draw() }`. 5. When the last `leave()` arrives, GCD submits the notify block to the main queue, and the constellation is drawn once. The snippet below collects results by hopping to the main queue before `leave()`, so the dictionary is only ever touched there and `notify` runs after every tile has been stored. ## notify versus wait | | `notify(queue:)` | `wait()` | |---|---|---| | Blocks a thread | no | yes, the calling thread | | Where the follow-up runs | the queue you pass | on the waiting thread, after it returns | | Safe on the main thread | yes | no: the screen freezes for the whole download | | Timeout | none built in | `wait(timeout:)` returns `DispatchTimeoutResult.success` or `.timedOut` | `notify` is the normal choice in app code. `wait` belongs on a background thread that has nothing else to do, and even there it holds a thread from the system pool for the whole time. ## Why async(group:) is not enough `DispatchQueue.async(group:execute:)` enters the group when the block is submitted and leaves it when the block **returns**. If the block only starts an asynchronous request, it returns at once, the group empties, and `notify` fires before any tile has arrived. `async(group:)` fits work that is synchronous inside the block, such as decoding data already in memory. For callback-based work, `enter()` and `leave()` are the tool, and the enter/leave pair is what the `DispatchGroup` documentation describes for tasks added "by a means other than" group submission. ## Collecting results safely The completions arrive on whatever queue the networking layer uses, often several at once. Writing them into a shared dictionary from those threads is a data race. Common fixes: - hop to the main queue to store each result, as the snippet does; - funnel writes through a private serial queue; - give each request its own slot in a pre-sized array and write it from one queue. In the Swift 6 language mode the closures handed to `DispatchQueue.async` are `@Sendable`, so mutating a captured local `var` from them is diagnosed by the compiler as well. ## Where async(group:) does fit `async(group:)` is the right call when the block itself does all the work before it returns. Decoding three tiles that are already in memory is an example: submit each decode with `DispatchQueue.global(qos: .userInitiated).async(group: group) { ... }`, and the group counts each block until it returns, with no `enter()` or `leave()` written by hand. Mixing both styles in one group is allowed, because both simply change the same count; what matters is that every unit of work is counted exactly once. ## Failure modes to recognise - **Missing `leave()`** on an error path: the count never reaches zero, `notify` never runs, and the constellation is never drawn. - **Extra `leave()`**, for example when a callback fires twice: invalid per the documentation, and the app stops. - **`notify` registered before any `enter()`**: the group is empty, and Apple's documentation says the block is submitted immediately, so drawing starts with no tiles. - **`wait()` on the main thread**: the UI freezes until every download finishes or the watchdog ends the app. - **`wait()` inside an `async` function**: the Swift overlay marks it unavailable from asynchronous contexts, with the message "Use a TaskGroup instead".
- What happens if one tile request never calls its completion handler?The group's count never reaches zero, so `notify` never fires and the constellation is never drawn; a `wait()` would block forever. Put a timeout on the request itself, or call `wait(timeout:)` from a background queue, which returns `.timedOut` instead of hanging. If a timeout path calls `leave()` early, make sure the late callback cannot call it a second time.
- Why does it matter whether notify(queue:) is called before or after the enter() calls?`notify` fires when the group is empty. Apple's documentation says that if the group has no outstanding work when you call it, the block is submitted immediately. Registering it before the first `enter()` therefore draws with no tiles. Enter for every request first, then register `notify`.
- Can an async function call DispatchGroup.wait() to wait for the tiles?No. The Swift overlay marks `DispatchGroup.wait()` and its timeout variants unavailable from asynchronous contexts, with the message "Use a TaskGroup instead". Parallel downloads inside async code move to a task group, which is covered with Swift's tasks.
- async(group:) is enough to track a request started inside the block.
- notify(queue:) blocks the calling thread until the group finishes.
- Calling leave() one extra time is harmless; the count just stays at zero.
- group.wait() on the main thread is fine because the downloads run elsewhere.
- The notify block runs once for every leave() call.