← C++

C++ · 12 / 24

Investigate data races with ThreadSanitizer

Compare unprotected shared writes with a synchronized implementation.

  • Large
  • Advanced
  • 90 min

Prerequisites: Background work, performance and desktop packages, Find memory errors with AddressSanitizer

In this tutorial
  1. Define the contract
  2. Separate tools and build
  3. Check observable expectations
  4. Detect an incorrect change
  5. Run the exercise separately
  6. Interpret the verification boundary
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

ThreadSanitizer requires a supported Linux environment. On an address-space conflict verify.py tries launching one process with setarch without ASLR. System-wide settings are not changed.

Verified on 2026-10-21 on Linux x86_64. The check requires an actual data-race finding and then validates the corrected counter. Some Linux environments need the documented setarch process launch. A sanitizer that cannot start does not count as passing.

A correct final value does not prove absence of data races. Two threads may access the same location without synchronization and occasionally still produce the expected result. ThreadSanitizer observes memory accesses. The mutex protects the complete update.

Package contents and individual files

01Define the contract

Two threads write to the same counter without synchronization in the negative example. ThreadSanitizer detects the data race. The correction uses atomic access. An atomic counter does not make a multi-step business operation atomic.

main.cpp · cppOpen file
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <thread>
int main() {
  int count = 0;
  std::mutex mutex;
  auto increment = [&] {
    for (int i = 0; i < 10000; ++i) {
      std::lock_guard guard(mutex);
      ++count;
    }
  };
  std::jthread a(increment), b(increment);
  a.join();
  b.join();
  if (count != 20000)
    throw std::runtime_error("Lost update");
  std::cout << "count=20000\n";
}

Run / check

python3 verify.py

02Separate tools and build

Put all files in a new folder. Read the compiler options and run verify.py. A failed command must propagate its exit code to the caller.

verify.py · pyOpen file
import os, subprocess, sys

flags = [
    "g++",
    "-std=c++20",
    "-g",
    "-O1",
    "-fno-omit-frame-pointer",
    "-fsanitize=thread",
    "-pthread",
    "-no-pie",
]
for source, name in [("broken.cpp", "broken"), ("main.cpp", "fixed")]:
    subprocess.run(flags + [source, "-o", name], check=True)
    env = dict(
        os.environ, ASAN_OPTIONS="detect_leaks=0", TSAN_OPTIONS="halt_on_error=1"
    )
    result = subprocess.run(["./" + name], capture_output=True, text=True, env=env)
    if "unexpected memory mapping" in result.stderr:
        import platform

        result = subprocess.run(
            ["setarch", platform.machine(), "-R", "./" + name],
            capture_output=True,
            text=True,
            env=env,
        )
    if name == "broken":
        expected = "data race"
        if not result.returncode or expected not in result.stderr:
            print(result.stderr)
            sys.exit(
                "Sanitizer did not demonstrate the expected defect. Check host support."
            )
        print("Expected sanitizer diagnosis:", expected)
    else:
        if result.returncode:
            print(result.stderr)
            sys.exit(result.returncode)
        print(result.stdout.strip())

03Check observable expectations

The check requires an actual data-race finding and then validates the corrected counter. Some Linux environments need the documented setarch process launch. A sanitizer that cannot start does not count as passing.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.20)
project(learning LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(lesson main.cpp)
enable_testing()
add_test(NAME behaviour COMMAND lesson)
Expected result

The check requires an actual data-race finding and then validates the corrected counter. Some Linux environments need the documented setarch process launch. A sanitizer that cannot start does not count as passing.

04Detect an incorrect change

Change a checked condition or expected result. Verification must now fail. Restore the original version afterwards. A green process alone does not explain which property is protected.

05Run the exercise separately

Replace the mutex with std::atomic<int> for this single counter.

06Interpret the verification boundary

Relaxed is sufficient here because the counter publishes no other data and join waits for both threads. Multiple related fields need a shared synchronization contract.

Expected result

Verification finishes successfully and checks the conditions named in the example.

Your exercise

Replace the mutex with std::atomic<int> for this single counter.

Show the solution and explanation

Relaxed is sufficient here because the counter publishes no other data and join waits for both threads. Multiple related fields need a shared synchronization contract.

solution.cpp · cppOpen file
#include <atomic>
#include <stdexcept>
#include <thread>
int main() {
  std::atomic<int> count{0};
  auto increment = [&] {
    for (int i = 0; i < 10000; ++i)
      count.fetch_add(1, std::memory_order_relaxed);
  };
  std::jthread a(increment), b(increment);
  a.join();
  b.join();
  if (count.load() != 20000)
    throw std::runtime_error("Lost update");
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.