Understanding sanitisers

Table of Contents

Thread Sanitizer (TSan)

ThreadSanitizer (TSan) is a runtime analysis tool that detects data races in multithreaded C and C++ programs. A data race occurs when two or more threads access the same memory location concurrently, at least one access is a write, and the accesses are not properly synchronized.

TSan works through compiler instrumentation. When a program is compiled with -fsanitize=thread, the compiler inserts additional monitoring code around memory accesses (reads and writes) and synchronization operations such as mutex locks, unlocks, and atomic operations.

During execution, the TSan runtime tracks memory accesses performed by each thread and records synchronization events. If it detects conflicting accesses to the same memory location without a valid synchronization relationship, it reports a data race along with a detailed stack trace showing where the accesses occurred.

Since TSan is a dynamic analysis tool, it can only detect races in code paths that are actually executed. If a buggy code path is never reached during testing, the race will remain undetected. In addition, some races depend on specific thread scheduling and timing, meaning multiple test runs may be required to reproduce and identify intermittent ("flaky") bugs.

The additional monitoring performed by TSan comes at a significant cost. Programs typically run several times slower and consume substantially more memory than normal builds. For this reason, TSan is commonly used during development and testing rather than in production environments.

1g++ -fsanitize=thread -g -O1 my_program.cpp -o my_program