What is Grand Central Dispatch (GCD)?
Answer
Grand Central Dispatch (GCD) is Apple's low-level C API (also available in Swift via Dispatch) for managing concurrent operations across a thread pool. It abstracts thread management — you submit work to queues, GCD decides which thread to use. Dispatch queues: Main queue: serial, runs on the main thread — all UI updates MUST happen here: DispatchQueue.main.async { self.tableView.reloadData() // UI update on main thread }. Global queues: concurrent, different quality-of-service (QoS) levels: DispatchQueue.global(qos: .userInitiated).async { let data = self.fetchData() // Background work DispatchQueue.main.async { self.updateUI(data) // Back to main } }. Custom queues: let serialQueue = DispatchQueue(label: "com.app.serial") let concurrentQueue = DispatchQueue(label: "com.app.concurrent", attributes: .concurrent). QoS levels (priority): .userInteractive (highest — animations), .userInitiated (user-triggered actions), .default, .utility (background tasks), .background (lowest — indexing, sync). sync vs async: sync blocks the calling thread until work completes; async returns immediately, work runs in background. Never call sync on the main queue from the main thread — deadlock! DispatchGroup: wait for multiple async tasks: let group = DispatchGroup() group.enter(); asyncTask1 { group.leave() } group.enter(); asyncTask2 { group.leave() } group.notify(queue: .main) { self.allDone() }. DispatchWorkItem: encapsulate work that can be cancelled. DispatchBarrier: read/write synchronization on concurrent queues.