skip to content

With GCD, why does a star-map screen hang or crash when main-thread code calls DispatchQueue.main.sync, and how do you prevent it?

level: seniorimportance: must knowfreq 62%

answer

  1. sync waits for its block
  2. main-queue items need the main thread
  3. a thread waiting on itself
  4. __DISPATCH_WAIT_FOR_QUEUE__ at the top of the crash
  5. dispatchPrecondition(condition: .onQueue(.main))

basics

~20 s

DispatchQueue.main.sync blocks the caller until its block has run on the main thread, but the caller is the main thread, so the block can never start: a deadlock. Use DispatchQueue.main.async instead, and assert queue expectations with dispatchPrecondition.

solid answer

~50 s

`sync` returns only after its block has finished, and the main queue runs blocks only on the main thread. When main-thread code calls `DispatchQueue.main.sync`, the main thread stops to wait for a block that only the main thread can run: a deadlock, which Apple's `DispatchQueue` documentation warns about. Current libdispatch usually detects a thread waiting on a queue it is already running and stops the app with `EXC_BREAKPOINT`, the crash's top frame reading `__DISPATCH_WAIT_FOR_QUEUE__`; a cycle across two threads, such as a background block holding a serial queue through `sync` and calling `main.sync` while the main thread waits on that same queue, is not detected and simply hangs. Prevent it by hopping with `DispatchQueue.main.async`, by giving each function one queue contract, and by asserting that contract with `dispatchPrecondition(condition: .onQueue(.main))`, which stops the app even in Release builds.

code

swift · 18 lines
swift
import UIKit

final class StarMapViewController: UIViewController {
    let titleLabel = UILabel()

    func applyTitle(_ title: String) {
        dispatchPrecondition(condition: .onQueue(.main))
        titleLabel.text = title
    }

    func titleArrived(_ title: String) {
        // Called from main-thread code AND from a background callback.
        // DispatchQueue.main.sync { applyTitle(title) }  // deadlocks on main
        DispatchQueue.main.async {
            self.applyTitle(title)
        }
    }
}

go deeper

for a junior

Recall that sync waits for its block and that DispatchQueue.main.sync from the main thread deadlocks, so UI hops use DispatchQueue.main.async.

for a middle

Explain why the block cannot start, using the facts that main-queue items run only on the main thread and that sync blocks the caller, and name the semaphore and group-wait variants.

for a senior

Read the evidence: a DISPATCH_WAIT_FOR_QUEUE crash versus a silent cross-thread hang, then fix with async hops, one queue contract per function and dispatchPrecondition checks that survive Release builds.

for a principal

Set the team rule that no code waits on the main thread, enforce queue contracts with dispatchPrecondition, and treat new main.sync calls as review blockers.

## What sync promises `DispatchQueue.sync(execute:)` submits a work item and **does not return until that item has finished**. The libdispatch header adds two details that explain the bug: - Calls to `dispatch_sync` that target the **current** queue result in deadlock, and `sync` is subject to the same multi-party deadlocks as a mutex, which is why the header prefers `async`. - As an optimisation, `sync` usually runs the item on the calling thread, **except** when the target is the main queue or a queue that targets it. Main-queue items must run on the main thread. Apple's `DispatchQueue` page states the consequence plainly in an Important note: attempting to synchronously execute a work item on the main queue results in deadlock. ## Why the main queue cannot serve its own thread Follow a call from a button handler on a star-map screen: 1. The handler is already running on the main thread. 2. It calls `DispatchQueue.main.sync { applyTitle(title) }`. 3. `sync` blocks the main thread until the block has finished. 4. The block is queued on the main queue, which runs only on the main thread. 5. The main thread is blocked in step 3, so the block never starts, and `sync` never returns. The usual origin is a helper written for background callers, "make sure this runs on main", that later gets called from main-thread code as well. ## Crash or hang: what you see | Situation | Typical symptom | |---|---| | Main-thread code calls `DispatchQueue.main.sync` | libdispatch usually detects it: `EXC_BREAKPOINT`, top frame `__DISPATCH_WAIT_FOR_QUEUE__` | | A serial queue's own work item calls `sync` on that queue | same detection and crash | | A background block holds serial queue A through `A.sync`, calls `main.sync`, while main waits in `A.sync` | silent hang: two threads each wait for the other | | Main thread blocked for too long by any wait | the app freezes; the watchdog may end it with `0x8badf00d` | So a crash with `__DISPATCH_WAIT_FOR_QUEUE__` points at a sync-on-own-queue call, while a frozen app with the main thread parked in a wait points at a cycle across threads or a blocking call. ## Other ways to block the main queue - **`DispatchSemaphore.wait()` on the main thread** for a callback that is delivered on the main queue: the `signal()` sits in a block the blocked thread can never run, the same deadlock without any `sync`. - **`DispatchGroup.wait()` on the main thread** for work whose completions hop to the main queue: same shape. - **Nested `sync`** on one serial queue, for example a cache getter that calls another getter which also calls `queue.sync`. - **Many blocked work items** on concurrent queues: Apple's documentation explains that each blocked item makes the system create more threads, and too many can exhaust the threads available to the app. ## Preventing it - **Default to `async`** for hops to the main queue. Most UI updates do not need to wait. - **Give every function one queue contract.** A function either runs on the main queue or never does; callers adapt, the function does not guess. - **Assert the contract** with `dispatchPrecondition(condition:)`, which takes a `DispatchPredicate`: `.onQueue(.main)`, `.notOnQueue(.main)` or `.onQueueAsBarrier(queue)`. Apple's documentation says that in `-O` builds, the Release default, a false condition still stops the program, and only `-Ounchecked` skips the check. - **Never call `sync` on a queue from code that may already be running on it**, and never take two queues with `sync` in different orders. - **Prefer completion handlers or notify blocks** to semaphores and group waits that block the main thread. ## Diagnosing a frozen screen When a tester reports that the star map froze rather than crashed, work through the evidence in order: 1. **Pause the app in the debugger** and read the main thread's stack. A main thread parked inside `sync`, `DispatchSemaphore.wait()` or `DispatchGroup.wait()` is the culprit, not the UI code above it. 2. **Find who holds what.** For a `sync` wait, look for another thread inside a work item on the queue the main thread is waiting for, and check whether that thread is itself waiting for the main queue. 3. **Read the queue labels.** Thread lists in the debugger and crash reports show each queue's `label`, which is why queues deserve reverse-DNS names such as `com.example.cache`. 4. **Break the cycle at the outermost wait**: turn one of the two `sync` calls into `async`, or make the background side hand its result over with `DispatchQueue.main.async` instead of waiting for the main queue. A crash report with `__DISPATCH_WAIT_FOR_QUEUE__` at the top needs no such hunt: the frame below it is the call that waited on its own queue.

  • Why is DispatchSemaphore.wait() on the main thread around a callback just as dangerous?
    If the callback is delivered on the main queue, its `signal()` sits in a block the blocked main thread can never run: the same deadlock without a `sync` call. Even when the callback arrives elsewhere, the main thread is frozen for the whole request, and Apple's main-queue documentation warns that an unresponsive main thread can end in a `0x8badf00d` watchdog termination.
  • What does dispatchPrecondition do in a Release build?
    It still checks. Apple's documentation says that in `-O` builds, Xcode's Release default, a false condition stops program execution; in `-Onone` it stops in a debuggable state; only `-Ounchecked` skips evaluation. That is why it suits queue contracts that must hold in shipping code, unlike `assert(_:_:)`, which `-O` builds do not evaluate.
  • How can blocking inside work items exhaust threads even without a deadlock?
    Apple's `DispatchQueue` documentation explains that when a task on a concurrent queue blocks its thread, the system creates more threads to run the remaining tasks, and if too many tasks block, the app may run out of threads. Dozens of tile downloads each waiting on a semaphore can do it. Use callbacks and `notify` instead of waits.

  • DispatchQueue.main.sync is safe on the main thread because it just runs the block inline.
  • dispatchPrecondition is compiled out of Release builds, just like assert.
  • A GCD deadlock always crashes, so a frozen screen must have another cause.
  • Waiting on a DispatchSemaphore from the main thread is fine with a long timeout.
  • Using main.sync for every UI hop keeps updates in order, which async cannot promise.