Skip to Content
Course content

242: Debugging Data Races with Thread Sanitizer

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I worked with a developer who spent nearly an entire week chasing a bug that only appeared on a physical iPhone 13, but never in the Xcode simulator. He was building a custom image caching system, and every few hundred requests, the app would just... vanish. No helpful crash log, just a SIGABRT or a random memory corruption error. He spent days auditing his logic, convinced there was some obscure edge case in the API response. The reality? He was writing to a Dictionary on a background thread while simultaneously reading from it on the main thread to update the UI. It was a classic data race, the kind of "Heisenbug" that disappears the moment you try to look at it with a debugger.

A data race happens when two or more threads access the same memory location concurrently, and at least one of those accesses is a write. In Swift, this is a recipe for disaster because many of our standard collections aren't thread-safe. The scary part is that your code might work perfectly for months, then crash in production the moment a user's device has enough CPU cores to actually run those operations at the exact same millisecond. This is where the Thread Sanitizer (TSan) comes in. It's not a static analyzer that looks at your code; it's a runtime tool that monitors memory access and screams the moment it sees a conflict.

Turning on the Watchdog

You won't find TSan running by default because it carries a heavy performance cost—your app will run significantly slower and consume more memory. But during the debugging phase, that's a trade-off you have to make. To get it running, you need to dive into your project's Scheme settings. Click on your target name next to the Run button in the top toolbar, select Edit Scheme..., and head over to the Diagnostics tab. There, you'll see a checkbox for Thread Sanitizer.

Once you check that box and run your app, Xcode starts tracking every single memory access. I usually recommend running your app through its "stress paths"—the parts of the UI where you're triggering lots of network requests or heavy data processing—because that's where the races are most likely to hide.

Decoding the TSan Report

When TSan catches a race, it doesn't just crash the app; it pauses execution and prints a detailed report in the console. At first glance, it looks like a wall of text, but you only need to look for two specific things: the Write and the Previous Read (or vice versa).

Thread 2: Write of size 8 at 0x600001234560 by thread T2
Thread 1: Previous read of size 8 at 0x600001234560 by thread T1

The magic is in the stack traces provided immediately below these lines. TSan tells you exactly which line of code performed the write and which line performed the read. If you see your ImageCache.save() method appearing in the "Write" trace and ImageCache.fetch() appearing in the "Read" trace, you've found your culprit. I've found that the most common mistake is thinking a DispatchQueue.main.async call "protects" the data; it only protects the UI update, not the underlying data structure you're accessing inside that block.

Eliminating the Race

Once you've identified the conflict, you have to synchronize the access. Since we've already moved past the basics of concurrency in this course, you know that the modern Swift way to handle this is using an actor. By moving your shared state—like that problematic Dictionary—into an actor, Swift guarantees that only one task can access that state at a time, effectively turning the "race" into a "queue."

If you're working in a legacy codebase where actors aren't an option, you can use a concurrent DispatchQueue with a barrier flag for writes. This allows multiple simultaneous reads but ensures that when a write happens, it has exclusive access to the memory. Personally, I always push for actors now; they turn these runtime crashes into compile-time errors, which is a much friendlier way to spend your Tuesday afternoon.




📋 Practical Task

Fixing the Concurrent User Session Race

You have been handed a SessionManager class that is causing intermittent crashes in a production app. The manager tracks active user sessions in a dictionary, but it's being accessed from multiple background threads during a sync process.

class SessionManager {
    var activeSessions: [String: Date] = [:]

    func updateSession(userId: String) {
        // This is called from various background threads
        activeSessions[userId] = Date()
    }

    func getSession(userId: String) -> Date? {
        // This is called from the main thread for UI updates
        return activeSessions[userId]
    }
}

// Simulation of the race
let manager = SessionManager()
for i in 0...1000 {
    DispatchQueue.global().async {
        manager.updateSession(userId: "user_\(i % 10)")
    }
    DispatchQueue.main.async {
        _ = manager.getSession(userId: "user_\(i % 10)")
    }
}

Your Task:

  • Create a new Xcode project and paste the code above into a command-line tool or a simple View Controller.
  • Enable the Thread Sanitizer in the Scheme Diagnostics.
  • Run the app and observe the TSan warning in the console. Identify the exact lines causing the conflict.
  • Refactor the SessionManager into an actor to resolve the data race.
  • Update the simulation code to use await when calling updateSession and getSession.
  • Run the app again with TSan enabled to verify that the data race is gone.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.