OperationQueue vs GCD

Concurrency Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Without async/await, you need: at most 3 downloads at once, unzip only after its download, and cancel all when the user leaves. Which fits best?

Options
Hint 1 of 1

Which API has dependencies built in?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B OperationQueue with maxConcurrentOperationCount = 3 and dependencies

Correct. It provides all three features.

Why not the others?
  • A A concurrent DispatchQueue. It has no dependencies, no limit and no way to cancel queued work.
  • C DispatchSemaphore(value: 3) around a global queue. It limits concurrency by blocking threads, and has no dependencies or cancellation.
  • D A Thread per file. Threads are expensive and give you none of these features.

30-second answer

OperationQueue is built on GCD but adds dependencies between operations, a max concurrency limit, cancellation of individual operations, and observable state. It suits pipelines of long-lived work in older code. In new code, task groups and structured concurrency usually cover the same needs.

Practise saying it · 30 s. No recording, just a timer

Compare OperationQueue and GCD.

Say your answer out loud, then check which of these points you covered:

  • Dependencies
  • Concurrency limit
  • Cancellation
  • Task groups in new code

Deep dive

addDependency runs an operation only after another finishes.

maxConcurrentOperationCount limits parallelism without semaphores.

cancel() marks operations; subclasses must check isCancelled.

Async work inside an Operation needs a custom asynchronous subclass, which is tricky to write.

Common mistakes

  • Using DispatchSemaphore to limit concurrency (it blocks threads).
  • Forgetting that cancel is cooperative for operations too.
  • Writing new asynchronous Operation subclasses instead of using async/await.

Senior take & follow-ups

Seniors map Operation features to their structured-concurrency equivalents.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you limit a TaskGroup to 3 at a time?

    Show hint

    Seed 3 tasks, then add one per next().

  2. What is a BlockOperation?

    Show hint

    An operation built from one or more closures.

Suggest a fix if something here is wrong or out of date.