← Lessons

quiz vs the machine

Gold1470

Concurrency

The Thread Sanitizer

A tool that detects data races by tracking happens before order.

5 min read · core · beat Gold to climb

The Thread Sanitizer

A thread sanitizer is a dynamic analysis tool that catches data races as a program runs. A data race is two threads accessing the same memory, at least one writing, with no synchronization ordering between them. Such bugs are notorious because they may surface only rarely under specific timing.

The sanitizer instruments every memory access and every synchronization event. It builds a happens before graph that records ordering created by locks, atomics, and thread joins. When it sees two accesses to the same location from different threads, at least one a write, and no happens before edge connects them, it reports a race with both stack traces.

  • Finds races even when they did not corrupt data on that run, because it reasons about ordering, not symptoms.
  • Only sees executed code paths so coverage matters, an unexercised race goes unnoticed.
  • Costly It slows the program several times over and uses extra memory, so it runs in testing, not production.

The key strength is that it does not rely on a race actually misbehaving. As long as the racing accesses execute, the missing ordering is detected, turning rare nondeterministic crashes into a clear deterministic report.

Key idea

A thread sanitizer builds a happens before graph from synchronization events and flags any two unordered conflicting accesses as a data race.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a thread sanitizer track to decide if two accesses race?

2. Why might a real race still go undetected by the sanitizer?