Section 10.25

ThreadSanitizer

Full name: ThreadSanitizer, usually shortened to TSan. The name joins the words thread and sanitizer; it is not an abbreviation.

Definition

ThreadSanitizer (TSan) is a sanitizer §10.21 in the Clang §12.17 compiler, a set of checks added to a program when it is compiled, that detects data races §9.3 in C and C++ programs while they run. A data race is two accesses to the same memory location from different threads, at least one a write and at least one not atomic (not performed as one indivisible step), with no synchronization that orders one before the other. TSan reports a race even when the two accesses did not overlap in time.

The idea

Two threads each run hits = hits + 1 on a shared int with no lock. The statement is three machine steps, load, add and store, and if both threads load before either stores, one increment is lost. A test that runs the threads a thousand times usually prints the right total, because the bad interleaving needs both threads inside those three steps at once. The program is wrong anyway: C and C++ make a data race undefined behavior §4.12, so the compiler may, for example, keep hits in a register throughout a loop.

TSan does not wait for the bad interleaving. For each pair of conflicting accesses, it asks whether a chain of synchronization, such as one thread releasing a lock that the other then acquires, forced one access to come before the other. If not, another schedule could have swapped or overlapped them, so TSan reports the race from a run in which nothing went wrong. The same question marks the tool’s limit. When every access is correctly ordered, but a condition checked under one lock is acted on under another, the outcome still depends on timing, which is a race condition §9.2, yet there is no data race to report.

How it works

  1. Instrumentation §14.24. With -fsanitize=thread, the compiler inserts a call to the TSan run-time library before every load and store, passing the address, the size, whether the access is a write and whether it is atomic.

  2. Synchronization. The run-time library intercepts thread creation and joining, the locking and unlocking of each mutex §9.5 (a lock that one thread at a time can hold), and atomic operations §9.8. Each of these creates happens-before ordering §9.10, the relation that guarantees one event is ordered before, and visible to, another. Unlocking a mutex mm happens before the next locking of mm, and creating a thread happens before the thread’s first action.

  3. Vector clocks. Each thread tt keeps a vector clock CtC_t, one counter per thread. Ct[t]C_t[t] counts tt’s own steps, and Ct[u]C_t[u] is the latest step of thread uu known to happen before tt’s current point. A release merges the thread’s clock into a clock kept for the lock; an acquire raises each counter of the thread’s clock to the lock’s value wherever that value is larger.

  4. Shadow memory. For each 8 bytes of program memory, a few shadow cells each record one recent access: the thread, its counter at the time, the bytes touched, write or read, atomic or not.

  5. The check. When thread tt accesses a location, TSan compares the access with each stored access by another thread uu, made at counter value ee. If at least one of the two is a write, at least one is not atomic, and e>Ct[u]e > C_t[u], then tt has not synchronized with uu since that access, and TSan prints WARNING: ThreadSanitizer: data race with the stack traces of both accesses.

TSan also reports misuse of locks, such as lock-order §9.15 inversions, in which two threads take the same two locks in opposite orders and could reach a deadlock §9.14. The Clang documentation gives a typical slowdown of 5 to 15 times and a memory overhead of 5 to 10 times. TSan needs a 64-bit host operating system and cannot share a build with AddressSanitizer §10.22 or MemorySanitizer §10.24. Synchronization that it cannot see, such as a lock written in assembly, can be described to it with annotation functions such as __tsan_acquire and __tsan_release. The race detector of the Go language uses the same run-time library.

Worked example

A data race that does no harm in this run. The counter values are illustrative. The main thread creates threads A and B. Thread A runs hits = 1 when its own counter is 3, and finishes. Only later in time does B run x = hits. B’s clock holds CB[A]=0C_B[A] = 0, because nothing has ordered any step of A before B: no lock and no join connects them. TSan compares the stored write, made by A at counter 3, with B’s read. Since 3>03 > 0, one access is a write and neither is atomic, TSan reports a data race, although the accesses were far apart in time and x received the expected 1.

Now let A unlock a mutex mm after its write, at counter 4, and let B lock mm before its read. The lock’s clock records A at 4, and B’s acquire takes the maximum: CB[A]=max(0,4)=4C_B[A] = \max(0, 4) = 4. Since 3>43 > 4 is false, the write happens before the read, and TSan stays silent.

A wrong result that is not a data race. An atomic counter c holds 5. Threads A and B each run v = atomic_load(&c); atomic_store(&c, v + 1);. In one schedule, A loads 5, B loads 5, A stores 5+1=65 + 1 = 6 and B stores 5+1=65 + 1 = 6. The final value is 6, but two increments should give 5+2=75 + 2 = 7. Every access is atomic, so there is no data race, the C standard defines the behavior, and TSan reports nothing. The defect is that the increment as a whole is not one atomic operation. atomic_fetch_add(&c, 1) makes it one: the two calls turn 5 into 6 and 6 into 7, in either order.

Stated precisely

The C11 standard (section 5.1.2.4) defines the property that TSan checks. Two evaluations conflict when one of them modifies a memory location and the other reads or modifies the same location. An execution contains a data race when it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. A data race is undefined behavior.

In one run, TSan reports a pair of accesses aa and bb when all of these hold:

  1. both executed in this run, in instrumented code;

  2. they touch overlapping bytes, from different threads;

  3. at least one is a write, and at least one is not atomic;

  4. no happens-before path connects them through synchronization that TSan observed;

  5. the earlier access is still among the few accesses that the shadow cells remember.

If all code is instrumented and all synchronization is visible to TSan, every report is a data race of this run. Without that assumption, synchronization that TSan missed produces false positives §1.22. Silence never proves that a program is free of data races: other inputs, other schedules, forgotten history and uninstrumented code all escape it.

Limits and common mistakes

TSan does not find a race condition built from correctly synchronized steps: a check and the action that depends on it placed in two separate critical sections §9.4 (a critical section is code that runs while holding a lock), or a read-modify-write built from a separate atomic load and atomic store. Each needs a test oracle §10.5 that checks the intended property, as the answer below explains.

Incidental synchronization hides races. If in this schedule both threads happen to take an unrelated logging lock between the two accesses, the accesses are ordered in this run and TSan stays silent; in another schedule they are not ordered.

Only executed code and observed synchronization count. The slowdown changes the schedule, so a run under TSan explores different interleavings from the normal build, not more of them. An uninstrumented library hides its own accesses, and if it synchronizes internally, TSan can report races that this synchronization in fact prevents.

A host build checks host threads. TSan does not model an interrupt handler §6.12 preempting a thread on a microcontroller §6.1, hardware that writes memory directly, or the disabling of interrupts §6.11 used as a lock. Firmware logic moved to the host is checked only as the threads of that host build.

Questions answered

Can it find a logical race in correctly synchronized state transitions?

No: ThreadSanitizer (TSan) detects data races, and correctly synchronized state transitions contain none, so TSan stays silent even when the transitions are combined wrongly. A data race is a pair of accesses from different threads, at least one a write and at least one not atomic, that no synchronization orders. A logical race is an outcome that depends on timing although every single access is atomic or made under a lock. In one example, a thread reads a state under a lock, releases the lock, and sets a new state under the lock again, while another thread does the same in between. In another, a counter is incremented with a separate atomic load and atomic store, so that two increments from 5 give 6 instead of 7.

Finding a logical race needs a statement of the intended property and a test oracle that checks it, for example that the counter equals the number of increments, or that at most one job runs at a time. The property is then checked over many schedules: by stress testing, by tools that perturb the scheduler, or by model checking §3.30, which explores the possible interleavings systematically. TSan’s part is narrower. It shows that the executed paths contained no data race, and it reports a logical race only when the faulty code also happens to contain an unsynchronized access.

Related entries: Sanitizer (§10.21), Race condition (§9.2), Data race (§9.3), Happens-before relation (§9.10), Linearization point (§8.6), Atomic operation (§9.8), Mutex (§9.5). Further reading: [106].