ConcurrencyMidMCQ

What is `OperationQueue` and how is it different from GCD?

Test your knowledge:

Explanation & Code

Answer: OperationQueue is a higher-level abstraction over GCD. It adds features like dependencies between operations, cancellation, and maximum concurrency limits.

OperationQueueGCD
Dependencies✅ Yes❌ No
Cancellation✅ YesLimited
Max concurrency✅ YesLimited
KVO observable✅ Yes❌ No
OverheadHigherLower

Code Example:

let queue = OperationQueue()
queue.maxConcurrentOperationCount = 3

let op1 = BlockOperation { print("Download image") }
let op2 = BlockOperation { print("Process image") }
let op3 = BlockOperation { print("Save image") }

// op2 and op3 won't start until op1 finishes
op2.addDependency(op1)
op3.addDependency(op2)

queue.addOperations([op1, op2, op3], waitUntilFinished: false)

// Cancel all
queue.cancelAllOperations()

Rate your understanding:

Ready to practice more Concurrency?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.