The Data Race Problem
Understand why concurrent mutation is unsafe.
What Is a Data Race?
A data race happens when two or more threads access the same memory location concurrently, at least one access is a write, and there is no synchronization between them.
The result is undefined behavior: corrupted values, crashes, or bugs that only appear under load.
Shared Mutable State
The root cause of data races is shared mutable state. If many tasks can read and write the same variable, ordering becomes unpredictable.
The counter below can lose increments because count += 1 is read-modify-write, not atomic.
final class Counter {
var count = 0
func increment() {
count += 1 // read, add, write: not atomic
}
}All lessons in this course
- The Data Race Problem
- The Sendable Protocol
- Actor Isolation and nonisolated
- Migrating to Strict Concurrency