# Detecting race conditions

## In this learning path

- [Introduction](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/)
- [Introduction to C++ Memory Models](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/1/)
- [The C++ Memory Model and Atomics](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/2/)
- [Walk through a Race condition example](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/3/)
- [Detecting race conditions](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/4/)
- [Next Steps](https://learn.arm.com/learning-paths/servers-and-cloud-computing/arm-cpp-memory-model/_next-steps/)

## How can I detect infrequent race conditions?
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++` or `g++`:

```bash
clang++ relaxed_memory_ordering.cpp -o relaxed_memory_ordering_tsan -fsanitize=thread -fPIE -pie -g
./relaxed_memory_ordering_tsan
```

```bash
g++ relaxed_memory_ordering.cpp -o relaxed_memory_ordering_tsan -fsanitize=thread -static-libtsan -fPIE -pie -g -pthread
./relaxed_memory_ordering_tsan
```

The output will look similar to:

```
__output__
==================
__output__
WARNING: ThreadSanitizer: data race (pid=2892958)
__output__
  Read of size 4 at 0xfffff42007b0 by thread T2:
__output__
   ...
__output__
   ...
__output__
   ...
__output__
SUMMARY: ThreadSanitizer: data race /home/ubuntu/src/relaxed_memory_ordering.cpp:23:12 in threadB()
__output__
==================
```

This output highlights a potential data race in the `threadB` function, corresponding to the source code expression `n->x != 42`.

## Does TSan have any limitations?
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](https://github.com/google/sanitizers/wiki/threadsanitizercppmanual).
