Swift Academy · Lesson

The Data Race Problem

Understand why concurrent mutation is unsafe.

Lesson 1 of 413 steps

The Data Race Problem is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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 update

Tearing 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 another

The 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 = race

Swift 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.balance

Sendable 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.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “The Data Race Problem” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “The Data Race Problem”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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

  1. The Data Race Problem
  2. The Sendable Protocol
  3. Actor Isolation and nonisolated
  4. Migrating to Strict Concurrency
← Back to Swift Academy