The Data Race Problem
Understand why concurrent mutation is unsafe.
The Data Race Problem is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
}
}Why Increments Get Lost
The statement count += 1 compiles to three steps: load the value, add one, store it back.
If two threads load 5 at the same time, both store 6, and one increment vanishes.
// Thread A loads 5
// Thread B loads 5
// Thread A stores 6
// Thread B stores 6 <-- lost updateTearing of Larger Values
Beyond lost updates, concurrent writes to multi-word values (like a struct or a 64-bit value on some platforms) can tear: a reader sees half of one write and half of another.
struct Point { var x: Double; var y: Double }
var p = Point(x: 0, y: 0)
// Concurrent writes may leave x from one write and y from anotherThe Old Fix: Locks
Before Swift Concurrency, the classic remedy was a lock (mutex). Only one thread holds the lock at a time, serializing access.
Locks work but are easy to misuse: forgotten unlocks, deadlocks, and priority inversion.
import Foundation
final class SafeCounter {
private let lock = NSLock()
private var count = 0
func increment() {
lock.lock()
defer { lock.unlock() }
count += 1
}
}Serial Dispatch Queues
Another classic approach is a serial dispatch queue. All mutations are funneled onto one queue, so they never overlap.
import Foundation
final class QueueCounter {
private let queue = DispatchQueue(label: "counter")
private var count = 0
func increment() {
queue.async { self.count += 1 }
}
}Why Manual Synchronization Is Fragile
Locks and queues rely on discipline. The compiler does not check that every access is protected.
One unguarded read slips through and the race returns. There is no compile-time guarantee.
// Nothing stops a careless reader from doing this:
// let value = counter.count // unsynchronized read = raceSwift Concurrency Changes the Game
Swift Concurrency makes data-race safety a language feature rather than a convention.
Three tools cooperate: actor for protected mutable state, Sendable for safe-to-share types, and the compiler to enforce both.
actor Counter {
private var count = 0
func increment() { count += 1 }
}Actors Serialize Access
An actor guarantees that only one task runs its mutating code at a time. The runtime serializes access automatically.
You never write a lock; the actor model provides the synchronization.
actor BankAccount {
private(set) var balance = 0
func deposit(_ amount: Int) { balance += amount }
}Compile-Time Enforcement
The compiler refuses to let you touch actor-isolated state without going through the actor. Cross-actor calls become asynchronous (await).
This turns runtime races into compile-time errors.
let account = BankAccount()
// Must await: balance is actor-isolated
// let b = await account.balanceSendable Bounds What Crosses Threads
The Sendable protocol marks types that are safe to pass across concurrency boundaries.
The compiler blocks sending non-Sendable mutable state into another task, closing the race at the type level.
struct Money: Sendable {
let amount: Int
let currency: String
}Quick Check: Data Races
Test your understanding of what causes a data race.
Recap: The Data Race Problem
Data races come from shared mutable state accessed concurrently without synchronization, producing lost updates, tearing, and undefined behavior.
Old fixes (locks, serial queues) work but are unchecked and fragile. Swift Concurrency replaces convention with enforcement: actor isolates state, Sendable bounds what crosses boundaries, and the compiler verifies safety. The rest of this course explores those tools in depth.
Frequently asked questions
Is the “The Data Race Problem” lesson free?
Yes — the full text of “The Data Race Problem” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “The Data Race Problem”?
Understand why concurrent mutation is unsafe. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The Data Race Problem” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Data Race Problem
- The Sendable Protocol
- Actor Isolation and nonisolated
- Migrating to Strict Concurrency