How do you ensure thread safety when accessing shared resources in Swift?

Instruction: Describe techniques to guarantee that shared resources are accessed safely across multiple threads.

Context: This question addresses the candidate’s ability to implement concurrency controls and synchronization mechanisms in Swift to prevent race conditions and ensure data integrity.

Updated

Official answer

Choose one ownership and synchronization model for shared mutable state, and make every access follow it. A serial queue works only if reads and writes are confined to it; a lock works only if the same lock protects the complete invariant. Synchronously dispatching onto a serial queue already executing your work can deadlock.

An actor can encapsulate a compound check-and-update. This complete program accepts exactly one of two concurrent reservations for the single available item:

actor Inventory {
    private var available = 1
    func reserve() -> Bool {
        guard available > 0 else { return false }
        available -= 1
        return true
    }
    func remaining() -> Int { available }
}
@main struct Demo {
    static func main() async {
        let stock = Inventory()
        async let first = stock.reserve()
        async let second = stock.reserve()
        let results = await [first, second]
        assert(results.filter { $0 }.count == 1)
        let remaining = await stock.remaining()
        assert(remaining == 0)
    }
}

The reserve method has no suspension point between checking and decrementing. An actor may process other work when an async method suspends, so assumptions made before await may need revalidation afterward. Actor isolation prevents unsynchronized access to its isolated state; it does not make a sequence of separate calls an indivisible transaction or guarantee a fixed operating-system thread.

For synchronous code, use appropriately scoped locks and release them on all paths. Do not hold a thread lock across await or block Swift concurrency's cooperative threads with semaphore waits for async work. An atomic variable provides specific atomic operations and ordering guarantees; it does not automatically protect a multi-variable invariant.

Use Swift concurrency checking, relevant sanitizers and stress/invariant tests. These are evidence, not proof that every possible interleaving is safe. DAU is not a race-detection or thread-safety metric.

Swift concurrency, Actors and executors

Related Questions