Explain the concept of GCD and how you would use it to perform a complex series of tasks, ensuring thread safety.

Instruction: Discuss the principles of Grand Central Dispatch (GCD) in managing asynchronous tasks and concurrency in iOS. Provide an example where you'd use GCD to execute multiple dependent tasks in sequence, ensuring data integrity and thread safety.

Context: This question assesses the candidate's understanding of concurrency and asynchronous programming in iOS, specifically with GCD. It tests the ability to manage complex tasks safely across different threads, a critical skill in developing responsive and efficient iOS applications.

Updated

Official answer

Grand Central Dispatch schedules work on queues. A serial queue executes submitted blocks one at a time; a concurrent queue may overlap blocks. Queues are scheduling abstractions, not permanently dedicated threads. Protect shared state with a consistent queue or another explicit isolation mechanism; merely using a background queue does not make accesses elsewhere safe.

For a dependent parse → validate → transform → collect pipeline, one worker block can own all intermediate state. This complete Swift program uses GCD for the bounded worker task and a checked continuation to return its result without blocking the caller:

import Dispatch

enum BatchError: Error {
    case tooManyInputs
    case invalidInteger(index: Int)
    case overflow(index: Int)
}

func doubledIntegers(_ inputs: [String]) async throws -> [Int] {
    guard inputs.count <= 100 else { throw BatchError.tooManyInputs }
    return try await withCheckedThrowingContinuation { continuation in
        let queue = DispatchQueue(label: "example.integer-pipeline")
        queue.async {
            do {
                var output: [Int] = []
                for (index, text) in inputs.enumerated() {
                    guard text.utf8.count <= 32, let value = Int(text) else {
                        throw BatchError.invalidInteger(index: index)
                    }
                    let (result, overflow) = value.multipliedReportingOverflow(by: 2)
                    guard !overflow else { throw BatchError.overflow(index: index) }
                    output.append(result)
                }
                continuation.resume(returning: output)
            } catch {
                continuation.resume(throwing: error)
            }
        }
    }
}

@main
struct Demo {
    static func main() async throws {
        let values = try await doubledIntegers(["3", "-2", "0"])
        assert(values == [6, -4, 0])
        print(values)
    }
}

Save as Demo.swift and compile with swiftc -parse-as-library Demo.swift -o demo, then run it. Empty input returns an empty array; malformed or overflowing input fails the batch, with no partial result published. The input value is captured and the mutable output belongs only to the worker. This intentionally serial example teaches dependency order; it does not claim parallel speedup or implement cancellation of the queued work.

For truly independent asynchronous operations, a DispatchGroup can coordinate completion, but it only tracks work actually registered with it. A block that starts an asynchronous download and returns has not thereby registered the download's later parsing. Balance enter/leave across success and failure, and leave only after the final dependent stage. Never wait on the main thread for work that needs it; perform the final UI change on the main actor/queue.

Dispatch groups and completion, Swift concurrency and isolation

Related Questions