Skip to content
Commitwise
Menu
iOS Development

GCD and OperationQueue: queues, groups and cancellation

Grand Central Dispatch and OperationQueue, which most UIKit codebases and many SDKs still use. Main, serial and concurrent queues, async vs sync and the main.sync deadlock, QoS and thread explosion, DispatchGroup, semaphores and barriers, cancellable work items and operations with dependencies, and bridging callbacks to async/await.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A button that freezes the app forever. A “Done” message that never appears after three downloads. Thumbnails that flash the wrong photo while you scroll. All three are bugs in code that uses Grand Central Dispatch (GCD), the queue library behind DispatchQueue.

New Swift code uses async/await and actors (see Swift concurrency), but most production iOS apps still have years of GCD and OperationQueue code, many SDKs call you back on their own queues, and interviewers still ask “what’s the difference between sync and async?” and “when would you use an OperationQueue?”. You need to read this code, fix it and migrate it.

New to some of these? Open what you need, or skip ahead.

Basics:What is the main thread?

The main thread is the one thread that draws the screen and handles touches. All UI updates must happen on it. If it’s busy for more than a fraction of a second (a big file read, a network call), the app stops responding: scrolling stutters and buttons don’t react.

Basics:What is a queue?

A queue is a line of tasks waiting to run, first in, first out. In GCD you don’t create threads yourself: you put closures on a queue, and the system runs them on threads it manages.

Part Not started

Dispatch queues: main, serial and concurrent

GCD gives you three kinds of queues:

QueueRuns tasksUse for
DispatchQueue.mainone at a time, on the main threadevery UI update
DispatchQueue.global(qos:)many at once, on background threadsslow work: decoding, image processing
your own DispatchQueue(label:)one at a time (serial), on a background threadprotecting shared data, ordered work

You add work with async or sync:

  • async adds the closure to the queue and returns immediately. The caller keeps going.
  • sync adds 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")
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

Spot the bugTapping Save hangs the app

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 }
    }
}

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; async returns, sync waits.
  • sync onto the current serial queue (including main.sync from 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/OSAllocatedUnfairLock in new code.

Check this part

  1. What does DispatchQueue.main.async { … } do when called from the main thread?

  2. Where must you set imageView.image after resizing a photo in the background?

  3. What is thread explosion in GCD?

  4. What happens with async(flags: .barrier) on DispatchQueue.global()?

Put work on queues, not threads: DispatchQueue.main for UI, global queues by QoS for background work, private serial queues to protect state. async returns immediately; sync waits, and sync onto the queue you're already on deadlocks. Too many blocked tasks cause thread explosion.

Part Not started

Groups, work items and semaphores

Often you start several things and need to know when they’re all done: download three files, then show “Done”. A DispatchGroup counts unfinished tasks:

  • group.enter() before each task starts,
  • group.leave() when it finishes, however it finishes,
  • group.notify(queue: .main) { … } runs once the count is back to zero.

A DispatchWorkItem is a closure you can cancel before it runs. That’s how you debounce a search field: on every keystroke, cancel the pending search and schedule a new one 300 ms later with asyncAfter, so only the last one runs.

A DispatchSemaphore is a counter that makes threads wait: wait() takes a slot (blocking if none is free), signal() gives it back. It can limit how many uploads run at once, but it blocks the thread that waits. Never call wait() on the main thread.

DispatchGroup balances enter/leave like a counter: an extra leave crashes, a missing one means notify never fires (and wait blocks forever, so prefer notify or wait(timeout:)). Work submitted with queue.async(group:) enters and leaves automatically, but only for synchronous work inside the block: callback-based APIs need manual enter/leave. Use defer { group.leave() } at the top of the callback. DispatchWorkItem.cancel() only prevents a not-yet-started item from running; a running one must check isCancelled. DispatchSemaphore is ownerless, so no priority donation (QoS inversion warnings in Xcode’s thread performance checker), and using one to turn an async API into a sync one is the classic deadlock when the callback is delivered on the queue you’re blocking. Modern equivalents: async let and withTaskGroup replace groups, Task.sleep + task cancellation replaces work-item debouncing (or debounce in Combine and AsyncAlgorithms), and a task group that adds a new child only when one finishes replaces a semaphore for limiting concurrency.

final class SearchController {
    private var pendingSearch: DispatchWorkItem?

    func queryChanged(_ text: String) {
        pendingSearch?.cancel()                          // the previous keystroke's search won't run
        let item = DispatchWorkItem { [weak self] in
            self?.performSearch(text)
        }
        pendingSearch = item
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: item)
    }
}

Predict the output

A user types 'swift' quickly, one letter every 100 ms, into a field using the SearchController above. How many times does performSearch run, and with what text?

for (i, text) in ["s", "sw", "swi", "swif", "swift"].enumerated() {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 * Double(i)) {
        controller.queryChanged(text)
    }
}

“Done” that never shows

Spot the bugSync finished, but the spinner keeps spinning

Tap the line with the bug.

func syncAll(ids: [Int]) {
    let group = DispatchGroup()
    for id in ids {
        group.enter()
        api.fetchNote(id: id) { result in
            guard case .success(let note) = result else { return }
            self.store.save(note)
            group.leave()
        }
    }
    group.notify(queue: .main) {
        self.spinner.stopAnimating()
    }
}

Exerciseeasy

Three requests, one screen

A profile screen needs the user, their posts and their followers count, from three callback-based API calls: api.user(completion:), api.posts(completion:), api.followers(completion:), each calling back on a background queue with a Result. Load them in parallel and update the UI once, on the main queue, when all three have finished, showing whatever succeeded.

›

One DispatchGroup, three enter/leave pairs with defer. Store the results in local variables, and touch them only from one queue.

SolutionTry it yourself first
func loadProfile() {
    let group = DispatchGroup()
    let lock = NSLock()                          // callbacks arrive on background queues
    var user: User?, posts: [Post] = [], followers: Int?

    group.enter()
    api.user { result in
        defer { group.leave() }
        lock.withLock { user = try? result.get() }
    }
    group.enter()
    api.posts { result in
        defer { group.leave() }
        lock.withLock { posts = (try? result.get()) ?? [] }
    }
    group.enter()
    api.followers { result in
        defer { group.leave() }
        lock.withLock { followers = try? result.get() }
    }

    group.notify(queue: .main) {                 // all three done, on main
        self.render(user: user, posts: posts, followers: followers)
    }
}

The callbacks can run at the same time on different threads, so writes to the shared variables need a lock (or a serial queue). notify happens after every leave, so reading them in the notify block is safe. With async/await, the same thing is three async lets and one await.

Limiting concurrency, then and now

// GCD: blocks one thread per waiting upload. Never call from main.
let slots = DispatchSemaphore(value: 3)
let queue = DispatchQueue(label: "uploads", attributes: .concurrent)
for file in files {
    queue.async {
        slots.wait()
        defer { slots.signal() }
        uploader.uploadSync(file)
    }
}

// Swift concurrency: no thread is blocked while waiting.
try await withThrowingTaskGroup(of: Void.self) { group in
    var iterator = files.makeIterator()
    for _ in 0..<3 { if let file = iterator.next() { group.addTask { try await uploader.upload(file) } } }
    while try await group.next() != nil {
        if let file = iterator.next() { group.addTask { try await uploader.upload(file) } }
    }
}

The GCD version with 500 files queues 500 blocks, and each one parks a thread in wait(), which is exactly the thread explosion from the previous part. If you must stay with GCD, a serial “feeder” or OperationQueue with maxConcurrentOperationCount = 3 avoids it.

Deep diveThe semaphore deadlock in 'make it synchronous' codeInterview favorite

A common legacy helper turns an async call into a sync one: create a semaphore with value 0, start the request, wait(), and signal() in the completion handler. If the helper is called on the main thread and the library delivers its completion on the main queue (many do, by default), the main thread is blocked waiting for a callback that can only run on the main thread: a permanent hang.

Even when it works, it ties up a thread for the whole request, and inside Swift concurrency it can exhaust the cooperative pool. Replace it with an async wrapper (withCheckedThrowingContinuation) and make the callers async. Xcode’s thread performance checker flags wait() on the main thread and priority inversions caused by semaphores.

  • Groups: balanced enter/leave, defer { group.leave() }, notify over wait; async(group:) only covers synchronous work.
  • DispatchWorkItem.cancel() stops unstarted items only; debounce = cancel + asyncAfter.
  • Semaphores block threads, have no owner (no priority donation) and deadlock as async-to-sync bridges; modern code uses async let, task groups and continuations.

Check this part

  1. A DispatchGroup's notify never fires. What is the most likely cause?

  2. How do you run a search only after the user stops typing for 300 ms?

  3. Why does a semaphore-based "make this call synchronous" helper hang when called on main?

  4. What does DispatchWorkItem.cancel() do to an item that is already running?

DispatchGroup waits for several async tasks: every enter needs exactly one leave, on every path. DispatchWorkItem makes delayed work cancellable, which is how to debounce. Semaphores limit concurrency but block a thread: never wait on main and never inside async code.

Part Not started

OperationQueue and moving to async/await

An OperationQueue is a higher-level queue built on GCD. Each unit of work is an Operation object (often a BlockOperation), which gives you three things plain closures don’t:

  • A limit: maxConcurrentOperationCount = 3 runs at most three at a time; the rest wait without using threads.
  • Dependencies: resize.addDependency(download) makes resizing start only after the download finished.
  • Cancellation: operation.cancel() or queue.cancelAllOperations(), for example when a table cell scrolls off screen.

Cancellation doesn’t stop running code: it sets isCancelled = true, and your operation must check it and stop early.

Today, most new code uses async/await instead. You’ll still meet OperationQueue in image loaders, sync engines and older SDKs, and you’ll often connect old callback code to new async code with a continuation.

Operation is a state machine (isReady, isExecuting, isFinished, isCancelled, all KVO-observable). Synchronous subclasses override main(); asynchronous ones (wrapping a callback API) override start() and isAsynchronous and must emit KVO for isExecuting/isFinished themselves, which is the boilerplate everyone gets wrong: forget it and the queue never frees the slot. Dependencies work across queues; a cancelled operation counts as finished, so its dependents still run and must check their dependencies’ outcome. maxConcurrentOperationCount = 1 doesn’t guarantee FIFO order (readiness, priority and QoS can reorder): use dependencies or a serial DispatchQueue when order matters. addBarrierBlock (iOS 13) waits for everything queued before it; OperationQueue.main serializes on the main thread. Bridging to Swift concurrency: withCheckedThrowingContinuation wraps one callback (resume exactly once: twice crashes, never leaks the task and logs a warning), AsyncStream wraps repeated callbacks, withTaskCancellationHandler forwards task cancellation to the old API’s cancel method. During migration, keep the old callback API as the source of truth, add async wrappers, and move callers one at a time.

final class ThumbnailLoader {
    private let queue: OperationQueue = {
        let q = OperationQueue()
        q.maxConcurrentOperationCount = 3        // at most 3 at a time; no blocked threads
        q.qualityOfService = .userInitiated
        return q
    }()
    private var running: [IndexPath: [Operation]] = [:]

    func load(_ url: URL, for indexPath: IndexPath, completion: @escaping (UIImage?) -> Void) {
        var data: Data?
        let download = BlockOperation { data = try? Data(contentsOf: url) }   // synchronous inside the operation
        let resize = BlockOperation { [unowned download] in
            guard !download.isCancelled, let data else { return }
            let image = UIImage(data: data)?.preparingThumbnail(of: CGSize(width: 120, height: 120))
            OperationQueue.main.addOperation { completion(image) }
        }
        resize.addDependency(download)
        running[indexPath] = [download, resize]
        queue.addOperations([download, resize], waitUntilFinished: false)
    }

    func cancel(for indexPath: IndexPath) {
        running.removeValue(forKey: indexPath)?.forEach { $0.cancel() }
    }
}

Predict the output

b depends on a, and a is cancelled before the queue starts it. What is printed?

let a = BlockOperation { print("a ran") }
let b = BlockOperation { print("b ran") }
b.addDependency(a)
a.cancel()
OperationQueue().addOperations([a, b], waitUntilFinished: true)

The wrong photo in the cell

Spot the bugScrolling fast shows other people's avatars

Tap the line with the bug.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "user", for: indexPath) as! UserCell
    let user = users[indexPath.row]
    cell.nameLabel.text = user.name
    let op = BlockOperation {
        let image = ImageDownloader.downloadSync(user.avatarURL)
        OperationQueue.main.addOperation { cell.avatarView.image = image }
    }
    imageQueue.addOperation(op)
    return cell
}

Exerciseeasy

Wrap a callback API in async/await

An old SDK has LocationLookup.find(address: String, completion: @escaping (Result<Coordinate, Error>) -> Void). Write func coordinate(for address: String) async throws -> Coordinate so async code can call it.

›

withCheckedThrowingContinuation gives you a continuation; resume it once from the completion handler.

SolutionTry it yourself first
func coordinate(for address: String) async throws -> Coordinate {
    try await withCheckedThrowingContinuation { continuation in
        LocationLookup.find(address: address) { result in
            continuation.resume(with: result)     // exactly once, success or failure
        }
    }
}

// Usage:
let place = try await coordinate(for: "Knez Mihailova 1, Belgrade")

resume(with:) takes a Result directly. If the SDK could call the completion twice, or never (for example when the request is cancelled), guard it: resuming twice crashes, and never resuming leaves the caller waiting forever, which the “checked” continuation reports in the console.

What to use when

NeedLegacyToday
Run off main, come backglobal().async + main.asyncTask + @MainActor, or a nonisolated async function
Wait for severalDispatchGroupasync let, withTaskGroup
Protect stateserial queue, barrieractor, Mutex
Limit concurrencysemaphore, maxConcurrentOperationCounttask group feeding N at a time
Dependencies, pipelinesOperation.addDependencysequential awaits in one task
Cancelcancel() + isCancelledtask.cancel() + Task.checkCancellation()
Delay, debounceasyncAfter, DispatchWorkItemTask.sleep(for:) + cancellation

GCD remains the right tool where Swift concurrency doesn’t fit: a callback-based library that requires a specific DispatchQueue, real-time audio and other code that must never suspend, and DispatchSource timers and file-system events (though AsyncStream wrappers are common).

Deep diveWriting an asynchronous Operation subclassInterview favorite

To wrap a callback API in an Operation, you can’t just override main(): it returns before the callback arrives, and the queue would consider the operation finished. You override start(), report isAsynchronous = true, and manage isExecuting and isFinished yourself, sending willChangeValue(forKey:) and didChangeValue(forKey:) (or KVO-compliant property wrappers) so the queue notices. In start(), check isCancelled first and finish immediately if set; when the callback arrives, set executing to false and finished to true, in that KVO order.

Mistakes show up as queues that stall: an operation that never sends isFinished holds one of the maxConcurrentOperationCount slots forever, and its dependents never start. That boilerplate is the main reason teams moved such pipelines to async/await, where the task simply ends when the function returns.

  • OperationQueue = concurrency limit, cross-queue dependencies, KVO state, cooperative cancellation; a cancelled dependency still lets dependents run.
  • Async Operation subclasses override start() and emit isExecuting/isFinished KVO, or they hold a slot forever. maxConcurrentOperationCount = 1 isn’t FIFO.
  • Bridge with withCheckedThrowingContinuation (resume once), AsyncStream, withTaskCancellationHandler; migrate callers gradually. GCD stays for queue-bound APIs, real-time code and DispatchSource.

Check this part

  1. What does operation.cancel() do to an operation that is already running?

  2. How do you call a completion-handler API from async code?

  3. Operation b depends on a, and a is cancelled. Does b run?

  4. An asynchronous Operation subclass never sends KVO for isFinished. What happens?

OperationQueue adds what GCD lacks: a concurrency limit, dependencies between operations and cancellation you can query. Cancellation is cooperative and a cancelled dependency still lets dependents run. Bridge callback APIs to async/await with checked continuations, resumed exactly once.

Key takeaways

  • UI only on DispatchQueue.main; slow work on a global queue, then main.async back.
  • async returns at once, sync waits; main.sync from the main thread freezes the app.
  • A DispatchGroup needs a leave() for every enter(), on every path: use defer.
  • Cancel and debounce with DispatchWorkItem; limit and order work with OperationQueue; cancellation is always cooperative.
  • Wrap old callbacks in withCheckedThrowingContinuation to use them from async code.
  • Serial queues for state, target-queue hierarchies, QoS awareness; blocking on concurrent queues causes thread explosion.
  • Semaphores block threads, defeat priority donation and deadlock as async-to-sync bridges.
  • OperationQueue: limits, dependencies (cancelled counts as finished), cooperative cancellation, KVO for async subclasses.
  • Migrate with continuations, AsyncStream and cancellation handlers; keep GCD for queue-bound APIs and real-time code.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.