skip to content

A Swift app traps with 'Simultaneous accesses to …, but modification requires exclusive access' — why wasn't this a compile error, and how do you fix it?

level: seniorimportance: should knowfreq 25%

answer

  1. the compiler cannot see every access
  2. class properties, globals, escaping captures
  3. on in -O builds too
  4. previous access vs current access

basics

~20 s

Class stored properties, globals and escaping-captured variables are checked at run time because the compiler cannot see every access to them; from Swift 5 on, that check traps in release builds too. Finish the read before the long write starts.

solid answer

~50 s

Exclusivity is proven statically for local variables and `inout` parameters, including the struct values they hold. For **class stored properties**, **global variables** and **variables captured by escaping closures**, any code holding the object or the closure might touch them, so the compiler emits run-time bookkeeping instead: each long access is recorded, and an overlapping access traps with `Simultaneous accesses to …, but modification requires exclusive access`, followed by where the previous and current accesses began. Since Swift 5 this check is on in `-O` and `-Osize` builds as well. The typical cause is a callback that reads `self.items` while a method holds `items[i]` `inout`. Fix the structure, not the check: read what the callback needs before the loop, pass it as an argument, or copy the property to a local, mutate it, and assign it back.

code

swift · 23 lines
swift
struct Body {
    var position: Double
    var velocity: Double
}

final class World {
    var bodies: [Body] = [Body(position: 0, velocity: 1),
                          Body(position: 4, velocity: 2)]

    func forEachBody(_ update: (inout Body) -> Void) {
        for i in bodies.indices {
            update(&bodies[i])        // modify access to self.bodies lasts for the call
        }
    }
}

let world = World()
world.forEachBody { body in
    // Read of world.bodies while forEachBody holds a modify access to it.
    let damping = 1.0 / Double(world.bodies.count)
    body.velocity *= damping
}
print(world.bodies)

go deeper

for a junior

Recall that some exclusivity conflicts are only found when the code runs, and that the trap message names both accesses that overlapped.

for a middle

Explain which variables get dynamic enforcement, class stored properties, globals and escaping captures, and why the compiler cannot prove their accesses.

for a senior

Read the previous and current access lines in a crash report, know the check is live in -O builds since Swift 5, and restructure the callback instead of reaching for an opt-out.

for a principal

Weigh callback-heavy APIs on classes: handing a closure inout access while it can reach self invites these traps, so prefer signatures that pass the closure what it needs.

## Why the compiler lets it through Swift's **law of exclusivity** forbids overlapping accesses to one variable when one of them writes. Swift enforces it as strongly as each kind of variable allows: - **Static enforcement** covers local variables and `inout` parameters, including the struct values they hold. The compiler sees every access and reports `overlapping accesses to 'x', but modification requires exclusive access`. - **Dynamic enforcement** covers **class stored properties**, **global variables** (including variables in top-level code) and **local variables captured by escaping closures**. Any code that holds a reference to the object, or that runs the escaping closure later, can reach them, so the compiler cannot prove what overlaps what. For dynamically enforced variables the compiler inserts calls that **begin and end** each access. The runtime keeps the set of open accesses and, when a new one conflicts with an open one, prints a report and stops the process. Where the compiler *can* prove that two dynamic accesses always conflict, it may still report the error at compile time — a `swap(&global, &global)` is caught early. ## What the trap looks like ```swift final class World { var bodies: [Body] = [] func forEachBody(_ update: (inout Body) -> Void) { for i in bodies.indices { update(&bodies[i]) // modify access to self.bodies } } } world.forEachBody { body in let damping = 1.0 / Double(world.bodies.count) // read of world.bodies body.velocity *= damping } ``` Running it prints, then traps: ``` Simultaneous accesses to 0x…, but modification requires exclusive access. Previous access (a modification) started at …World.forEachBody(_:) + 408 Current access (a read) started at: … Fatal access conflict detected. ``` The two lines name the **open access** (a modification, inside `forEachBody`) and the **new access** (a read, inside the closure). That pair is the bug. ## Release builds trap too Swift 4 enforced dynamic exclusivity only in debug builds. **Since Swift 5, run-time exclusivity checks are on by default in optimized (`-O` / `-Osize`) builds**, so a conflict that hid in testing can crash in production. The checks can be turned off with `-enforce-exclusivity=unchecked`, but the conflict is still there; it simply becomes **undefined behaviour**. ## Fixing it Pick the fix that removes the overlap: 1. **Read first.** Compute what the callback needs before the long access starts: `let damping = 1.0 / Double(world.bodies.count)` and use `damping` inside the closure. 2. **Pass it in.** Change the callback's signature so the method hands the closure the values it would otherwise fetch from `self`. 3. **Copy, mutate, assign back.** Inside the method, `var copy = bodies`, run the loop on `copy`, then `bodies = copy`. The closure now reads the unchanged property, which is a different location from `copy`. Escape hatches that do **not** fix it: - **`@exclusivity(unchecked)`** on the property removes its run-time check; the overlap remains and is undefined behaviour. - **Making the class `final`** or the method `private` changes dispatch, not access duration. - **A lock** does not help: both accesses are on the same thread, and the read happens *inside* the write. ## Class properties are checked one by one Exclusivity on a class is tracked **per stored property**, not per object. A closure that reads `world.gravity` while `forEachBody` holds `bodies` is fine; only another access to `bodies` conflicts. That is why calling other methods on the same object during a long access is usually safe. | Kind of variable | Enforcement | Failure mode | |---|---|---| | local `var` not captured by an escaping closure, `inout` parameter | static | compile error | | class stored property | dynamic | run-time trap | | global or top-level variable | dynamic | run-time trap | | local captured by an escaping closure | dynamic | run-time trap | | memory behind an unsafe pointer | none | undefined behaviour | Races between threads are a different problem, covered with Swift's data-race safety; the trap in this example comes from two accesses on one thread.

  • Can a Swift class method call another method on the same object while it holds one of its properties inout?
    Yes, as long as the other method does not touch that same stored property. Class exclusivity is tracked per stored property, never for the whole object, so reading `world.gravity` while `bodies` is under modification is fine. Only a second access to `bodies` conflicts.
  • What does -enforce-exclusivity=unchecked change for this Swift crash?
    It removes the run-time checks, so the trap disappears, but the overlapping read still happens while the array is being modified. The program now has undefined behaviour instead of a clean crash, which is why fixing the access pattern is the only real fix.
  • Why can a local variable in Swift move from compile-time to run-time exclusivity checking?
    If it is captured by an escaping closure, the compiler can no longer see when the closure will run and touch it, so the variable gets dynamic enforcement. A variable captured only by non-escaping closures keeps static checking.

  • Run-time exclusivity checks are compiled out of release builds.
  • Wrapping the access in a lock fixes a Simultaneous accesses trap.
  • Exclusivity on a class covers the whole object, so any other method call conflicts.
  • @exclusivity(unchecked) makes the overlapping access safe.
  • This trap can only come from two threads racing on the property.