Pick the fix
A counter is incremented from a synchronous C callback on many threads and must stay synchronous. Which tool?
Hint 1 of 2
Can the caller await?
Hint 2 of 2
Which option actually protects the variable?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B Mutex<Int> from Synchronization with withLock { $0 += 1 }
Correct. A lock keeps the call synchronous and safe (OSAllocatedUnfairLock on iOS 16–17).
Why not the others?
- A An actor. Callers would have to await, which a synchronous callback can't do.
- C
DispatchQueue.main.sync { count += 1 }. It serializes work onto the UI thread and deadlocks if called on main. - D A plain
varin a class marked@unchecked Sendable. Nothing protects the variable, so concurrent increments lose updates.