How to answer
A data race is two threads accessing the same memory at the same time, at least one of them writing, with no synchronization; it's undefined behavior. A race condition is a logic bug where the result depends on timing or ordering, such as check-then-act, and it can happen even when every access is properly synchronized. Swift 6 language mode rules out data races at compile time, but race conditions are still a design problem: actor reentrancy across an await is the classic example.
Key points
- Data race: memory-level, unsynchronized concurrent access with a write; undefined behavior (crashes, torn values)
- Race condition: logic-level, outcome depends on interleaving; possible with actors and locks
- Swift 6 mode: unprotected shared mutable state (like a global
varmutated from GCD closures) is a compile error - Fixes for data races: actor,
Mutex,Atomic, or not sharing (immutableSendablevalues) - Runtime data races are still possible through
@unchecked Sendable,nonisolated(unsafe), unsafe pointers, and C/ObjC code; Thread Sanitizer finds them
If they dig deeper
Actors serialize access but are reentrant: when an actor method suspends at await, other calls can run and change state, so an invariant checked before the await may be false after it. Fix it by doing the check and the mutation without a suspension in between, or re-checking after the await. count += 1 is a read-modify-write, so even Atomic needs add (one operation), not a load then a store.
Common pitfalls
Using the two terms interchangeably. Assuming "it compiles in Swift 6" means "no concurrency bugs". Splitting one logical update across two withLock calls or two awaits. Silencing the compiler with nonisolated(unsafe) and reintroducing the race.
How to use it
Does not compile in Swift 6 mode (intentionally): the global var is shared mutable state with no isolation. (In a default-MainActor app target the global becomes main-actor state instead, and the mutations from the GCD closures are flagged.)
import Foundation
var count = 0 // error: var 'count' is not concurrency-safe because it
// is nonisolated global shared mutable state
func incrementTwice() {
DispatchQueue.global().async { count += 1 }
DispatchQueue.global().async { count += 1 }
}Fixes, depending on how callers access it:
import Synchronization
actor Counter { // async callers
private(set) var count = 0
func increment() { count += 1 }
}
let lockedCount = Mutex(0) // sync callers; multi-step updates
func increment() { lockedCount.withLock { $0 += 1 } }
let hits = Atomic<Int>(0) // a lone counter
func recordHit() { hits.add(1, ordering: .relaxed) }A race condition that compiles cleanly (actor reentrancy):
actor Account {
private var balance = 100
func withdraw(_ amount: Int) async -> Bool {
guard balance >= amount else { return false }
await logWithdrawal(amount) // suspension: another withdraw can run here
balance -= amount // may go negative: check is stale
return true
}
// Fix: deduct before the await (or re-check after it)
private func logWithdrawal(_ amount: Int) async {}
}Best practices
- Use Swift 6 language mode so data races become compile errors
- Pick actor (async),
Mutex(sync, multi-step), orAtomic(single value) for shared mutable state - Keep check-and-update together with no
awaitin between; re-validate state after every suspension in an actor - Run Thread Sanitizer in tests for code using
@unchecked Sendable,nonisolated(unsafe)or C/ObjC
Related concepts
- Thread safety, actors and reentrancy, Sendable, NSLock and Mutex, Thread Sanitizer, deadlock