ThreadSanitizer (TSan) is a concurrency bug detection tool that identifies data races in multi-threaded programs. By instrumenting code at compile time, TSan dynamically tracks memory operations, monitors lock usage, and detects inconsistencies in thread synchronization. When a potential data race is found, TSan provides detailed reports to help you debug.
Although its runtime overhead can be significant, TSan provides valuable insights into concurrency issues often missed by static analysis tools.
TSan is available in recent versions of the clang
and gcc
compilers.
Compile and run the following example using the clang++
compiler:
clang++ relaxed_memory_ordering.cpp -o relaxed_memory_ordering -fsanitize=thread -fPIE -pie -g
./relaxed_memory_ordering
The output will look similar to:
==================
WARNING: ThreadSanitizer: data race (pid=2892958)
Read of size 4 at 0xfffff42007b0 by thread T2:
...
...
...
SUMMARY: ThreadSanitizer: data race /home/ubuntu/src/relaxed_memory_ordering.cpp:23:12 in threadB()
==================
This output highlights a potential data race in the threadB
function, corresponding to the source code expression n->x != 42
.
While powerful, TSan has some notable drawbacks:
It identifies concurrency issues only at runtime, meaning code paths not exercised during testing remain unchecked.
It cannot instrument or fix race conditions in third-party binaries or libraries without source code access.
It introduces significant performance overhead, typically slowing programs by 2 to 20 times and requiring additional memory. This makes it challenging to use in large-scale or real-time systems.
For further information, see the ThreadSanitizer documentation .