Fix ThreadSanitizer "Data Race" Warnings — Read the Two Stacks, Fix the Shared Variable
A data race report names one variable, two threads, and two stacks. The variable is the bug. This guide takes one report apart line by line, shows why neither stack alone is the place to fix, and then removes the race two ways: a mutex that serializes both accesses, and an atomic variable whose accesses cannot race at all.
Written November 20, 2026 · Tested with GCC 13.3.0 · 16 min read
- The first error: two writers, one variable, no lock
- Reading the report: two stacks, one location
- Why the fix belongs at the variable
- Fix 1: one mutex around both accesses
Written November 20, 2026
Tested with GCC 13.3.0
What this guide is
WARNING: ThreadSanitizer: data race is ThreadSanitizer reporting that two threads accessed the same variable at overlapping times, at least one of the accesses was a write, and nothing synchronized the two accesses. A data race is not a style problem. In C++ a data race is undefined behavior: the program has no guaranteed meaning once one happens, even when the printed result still looks right. The report is the useful part. It names the variable, both accesses with their sizes, both stacks with file and line, and which thread created which. Read in order, those lines point at one shared variable and at every place that touches it without protection.
ThreadSanitizer is a compile-time instrument plus a runtime checker. Build with g++ -std=c++17 -fsanitize=thread -g -pthread and the compiler instruments memory accesses; run the program and the checker compares accesses from different threads as they happen. The -g puts the file and line in each stack. The -pthread links the thread support the examples need. The report prints to standard error and the program output to standard output; the transcripts below merge the two in the order they appear. Addresses, process and thread IDs, binary offsets, and BuildId values change from run to run. The sizes, line numbers, thread roles, and the location line do not.
The first error: two writers, one variable, no lock
The smallest reliable reproducer is a global counter that two threads both write in a loop, with no lock and no atomic anywhere:
#include <iostream>
#include <thread>
int shared = 0;
void writer_a() {
for (int i = 0; i < 100000; ++i) {
shared = i;
}
}
void writer_b() {
for (int i = 0; i < 100000; ++i) {
shared = i;
}
}
int main() {
std::thread t1(writer_a);
std::thread t2(writer_b);
t1.join();
t2.join();
std::cout << "done" << std::endl;
return 0;
}
$ g++ -std=c++17 -fsanitize=thread -g -pthread race.cpp -o race
$ ./race
==================
WARNING: ThreadSanitizer: data race (pid=<pid>)
Write of size 4 at 0xADDR by thread T2:
#0 writer_b() race.cpp:14 (race+0xOFF) (BuildId: <hash>)
#1 void std::__invoke_impl<void, void (*)()>(std::__invoke_other, void (*&&)()) /usr/include/c++/13/bits/invoke.h:61 (race+0xOFF) (BuildId: <hash>)
#2 std::__invoke_result<void (*)()>::type std::__invoke<void (*)()>(void (*&&)()) /usr/include/c++/13/bits/invoke.h:96 (race+0xOFF) (BuildId: <hash>)
#3 void std::thread::_Invoker<std::tuple<void (*)()> >::_M_invoke<0ul>(std::_Index_tuple<0ul>) /usr/include/c++/13/bits/std_thread.h:292 (race+0xOFF) (BuildId: <hash>)
#4 std::thread::_Invoker<std::tuple<void (*)()> >::operator()() /usr/include/c++/13/bits/std_thread.h:299 (race+0xOFF) (BuildId: <hash>)
#5 std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (*)()> > >::_M_run() /usr/include/c++/13/bits/std_thread.h:244 (race+0xOFF) (BuildId: <hash>)
#6 <null> <null> (libstdc++.so.6+0xOFF) (BuildId: <hash>)
Previous write of size 4 at 0xADDR by thread T1:
#0 writer_a() race.cpp:8 (race+0xOFF) (BuildId: <hash>)
#1 void std::__invoke_impl<void, void (*)()>(std::__invoke_other, void (*&&)()) /usr/include/c++/13/bits/invoke.h:61 (race+0xOFF) (BuildId: <hash>)
#2 std::__invoke_result<void (*)()>::type std::__invoke<void (*)()>(void (*&&)()) /usr/include/c++/13/bits/invoke.h:96 (race+0xOFF) (BuildId: <hash>)
#3 void std::thread::_Invoker<std::tuple<void (*)()> >::_M_invoke<0ul>(std::_Index_tuple<0ul>) /usr/include/c++/13/bits/std_thread.h:292 (race+0xOFF) (BuildId: <hash>)
#4 std::thread::_Invoker<std::tuple<void (*)()> >::operator()() /usr/include/c++/13/bits/std_thread.h:299 (race+0xOFF) (BuildId: <hash>)
#5 std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (*)()> > >::_M_run() /usr/include/c++/13/bits/std_thread.h:244 (race+0xOFF) (BuildId: <hash>)
#6 <null> <null> (libstdc++.so.6+0xOFF) (BuildId: <hash>)
Location is global 'shared' of size 4 at 0xADDR (race+0xOFF)
Thread T2 (tid=<tid>, running) created by main thread at:
#0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:1022 (libtsan.so.2+0xOFF) (BuildId: <hash>)
#1 std::thread::_M_start_thread(std::unique_ptr<std::thread::_State, std::default_delete<std::thread::_State> >, void (*)()) <null> (libstdc++.so.6+0xOFF) (BuildId: <hash>)
#2 main race.cpp:20 (race+0xOFF) (BuildId: <hash>)
Thread T1 (tid=<tid>, finished) created by main thread at:
#0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:1022 (libtsan.so.2+0xOFF) (BuildId: <hash>)
#1 std::thread::_M_start_thread(std::unique_ptr<std::thread::_State, std::default_delete<std::thread::_State> >, void (*)()) <null> (libstdc++.so.6+0xOFF) (BuildId: <hash>)
#2 main race.cpp:19 (race+0xOFF) (BuildId: <hash>)
SUMMARY: ThreadSanitizer: data race race.cpp:14 in writer_b()
==================
done
ThreadSanitizer: reported 1 warnings
Two facts in this transcript matter before any fix is discussed. First, the program did not stop at the report. It printed the report, finished both loops, printed done, and only then printed ThreadSanitizer: reported 1 warnings on the way out. A race report is a warning about behavior that already happened, not a crash at the access. Second, the exit status of this run is 66, not 0. The program returned 0 from main, and the checker still set the final status to 66 because a report was issued. A test suite that runs this binary fails on the status even though the program output looks complete.
The shape of the report held across repeated runs of this program: the current access is the write in writer_b at line 14 by thread T2, the previous access is the write in writer_a at line 8 by thread T1, and the summary names line 14. Both threads run the same loop shape, so either thread can in principle be reported first in a program like this. What does not change is the pair: the two writes to shared, at lines 8 and 14, are the two accesses in every report.
Reading the report: two stacks, one location
Read the report in five parts, top to bottom.
The header names the checker and the finding: WARNING: ThreadSanitizer: data race, with the process ID. The first access block is the access that completed the race: Write of size 4 at ... by thread T2. Size 4 is the size of an int on this platform, and the stack below it is the code that performed that write, frame #0 first: writer_b() at race.cpp:14, the shared = i; line in the second writer. The frames below #0 are the std::thread machinery that started the function, and they carry no fix.
The second access block starts with Previous write: the earlier access to the same address, also a write of size 4, by thread T1, with its stack at writer_a() at race.cpp:8. The word Previous is the ordering claim: this access happened with no synchronization between it and the first block's access, so the two are concurrent in the sense the checker uses. A report can also pair a write with a read: the first block then says Read of size 4 and the fix is the same, because one write is enough to make the pair a race.
The location line names the memory itself: Location is global 'shared' of size 4. That line is the work item. It tells you the variable, its size, and that it has static storage. A heap allocation prints a heap location with the allocation stack instead; a stack variable prints its owning frame. In every form, the location line identifies the one object both threads share.
The two creation blocks, Thread T2 ... created by main thread at: and the matching block for T1, show where each thread started: main at lines 20 and 19, the two std::thread constructions. These stacks answer which threads are involved when the access stacks alone do not make it clear. They are rarely where a fix goes.
The last lines close the report: SUMMARY: ThreadSanitizer: data race race.cpp:14 in writer_b() repeats the current access as the headline, and after the program ends, ThreadSanitizer: reported 1 warnings counts the reports for the whole run. One warning here means one racing pair was reported. It does not mean the program has only one race in it: the checker reports races it observes in the execution that actually ran, in code paths that actually executed.
Why the fix belongs at the variable
Neither stack is the bug on its own. The write at line 8 is correct code in a single-threaded program, and so is the write at line 14. The bug is the relationship between them: two threads reach one variable and no rule orders their accesses. That is why a fix applied inside only one of the two functions cannot work. Guarding writer_a with a lock while writer_b writes bare leaves the pair unsynchronized, and the report returns, with the roles possibly swapped. Every access to the shared variable has to follow the same rule: the same mutex held on every path, or the variable itself made atomic so that its own operations carry the rule. Fix the variable's access rule and both stacks become correct at once, without either function's logic changing.
There is a second reason the location line leads. Real reports rarely involve a variable named as plainly as shared. The two stacks may pass through layers of calls before frame #0 in each names the actual access, and the functions involved may each touch several shared objects. The location line cuts through that: it states the exact object whose accesses disagree, and the fix starts from every read and write of that object in the whole program, not from the two accesses in this one report.
Fix 1: one mutex around both accesses
The mutex fix keeps shared a plain int and adds one rule: no thread touches it without holding shared_mutex. Both writers take the same mutex with std::lock_guard around the write, so the writes cannot overlap and each write is ordered against the next:
#include <iostream>
#include <mutex>
#include <thread>
int shared = 0;
std::mutex shared_mutex;
void writer_a() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(shared_mutex);
shared = i;
}
}
void writer_b() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(shared_mutex);
shared = i;
}
}
int main() {
std::thread t1(writer_a);
std::thread t2(writer_b);
t1.join();
t2.join();
std::cout << "done" << std::endl;
return 0;
}
$ g++ -std=c++17 -fsanitize=thread -g -pthread fixed_mutex.cpp -o fixed_mutex
$ ./fixed_mutex
done
The program prints done and exits with status 0, with no report. std::mutex gives exclusive ownership: a thread owns the mutex from a successful lock until unlock, and other threads block in lock while it is owned. std::lock_guard ties that ownership to a scope, locking on construction and unlocking on destruction, so the unlock cannot be skipped by an early return inside the loop body. The lock is taken per write here, inside the loop, which is the smallest change from the racing version. Holding one lock across a whole loop is also correct for this program and cheaper, but it serializes the two threads entirely; the per-write form shows the rule at the exact line the report named.
The mutex protects exactly the code the programmer puts under it. If a third function later reads shared without taking shared_mutex, the race is back, and the report will name that new access against a locked one. The mutex is a convention every access must follow, not a property of the variable. That is the trade the atomic fix makes differently.
Fix 2: make the variable atomic
The atomic fix moves the rule into the variable. shared becomes std::atomic<int>, and both writers store through it:
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> shared{0};
void writer_a() {
for (int i = 0; i < 100000; ++i) {
shared.store(i);
}
}
void writer_b() {
for (int i = 0; i < 100000; ++i) {
shared.store(i);
}
}
int main() {
std::thread t1(writer_a);
std::thread t2(writer_b);
t1.join();
t2.join();
std::cout << "done" << std::endl;
return 0;
}
$ g++ -std=c++17 -fsanitize=thread -g -pthread fixed_atomic.cpp -o fixed_atomic
$ ./fixed_atomic
done
This run also prints done and exits with status 0, with no report. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined: atomic operations do not race with each other, and each read-modify-write operation is a single atomic step rather than a separate read and write. The default operations used here, store and the matching loads, are sequentially consistent, so the stores from the two threads are ordered into one total order and every store reads as a complete value.
State the limit precisely, because it decides which fix a real program needs. The atomic variable fixes accesses to that one variable. It does not protect a second variable that must change together with it, it does not make a check-then-act sequence on the value indivisible unless the sequence is written as one atomic operation such as compare_exchange, and it does not order accesses to other plain variables nearby. Two counters that must stay equal need a mutex, or a redesign. One counter that threads only increment, read, and write is exactly the atomic case. Pick by what the data is: one variable acting alone takes the atomic; a group of values with an invariant across them takes the mutex.
Exit status and run options, measured
The exit status is part of the report's contract with a test suite, so measure it instead of assuming it. For the racing program above, the plain run exits with status 66. That value is the documented default of the exitcode flag: the flags reference lists exitcode with default 66, described as overriding the exit status of the process if something was reported. Setting the flag changes only the status:
$ TSAN_OPTIONS=exitcode=42 ./race
That run prints the same report and exits with status 42. Use a distinct value when a harness needs to tell a race failure apart from other failures at a glance.
The second flag worth knowing is halt_on_error, documented with default 0 and described as exiting after the first reported error. Measured here:
$ TSAN_OPTIONS=halt_on_error=1 ./race
That run prints the same report, exits with status 66, and never prints done: the process ends at the first report instead of running to completion. Without the flag, the same program printed the report, finished its work, and printed done before exiting, also with status 66. The flag changes how much of the program runs after the first race, not the status and not the report itself. In a long test run, halting keeps the first report from being buried under later output. In a diagnostic run, leaving it off shows whether the same variable races at more than one site.
One startup failure is worth recognizing because it looks like a checker bug and is not one. On some kernels ThreadSanitizer aborts before main with a line of the form FATAL: ThreadSanitizer: unexpected memory mapping, followed by two addresses. The checker maps a large shadow region at startup and aborts when the address layout it finds is not the layout it can use. The GCC documentation notes that turning address space randomization off with setarch can be desirable for stable sanitizer output, and running the binary as setarch x86_64 -R ./race is a working way to start a build that hits this abort: the same binary then runs and reports normally. The abort happens before any program code runs, so it says nothing about whether the program races.
The exact rule: what counts as a race
Two accesses form a data race when they touch the same memory location, at least one of them writes, they can run concurrently, and no synchronization orders one before the other. Synchronization is anything that creates an ordering the checker can see: a mutex locked and unlocked around the accesses, atomic operations, thread creation and join, and the other primitives the runtime intercepts. Thread creation and join are why the reads of shared after both joins in a longer version of these programs would not race: the joins order the writers before the read. The checker only reports races in executions that happen. A racing path the test never runs produces no report, so a clean run proves the executed paths were ordered, not that every path in the program is ordered.
ThreadSanitizer cannot be combined with AddressSanitizer or LeakSanitizer in one build: GCC documents -fsanitize=thread as incompatible with -fsanitize=address and -fsanitize=leak, so a program that needs both checks is built twice and run twice, once per checker. Its run-time behavior is set through TSAN_OPTIONS, and the flags reference is the list of supported options.
The fixes, ranked
- First, find every access to the variable named in the location line, not only the two in the report. The fix has to cover all of them or the report returns with a new pair.
- Second, if the variable acts alone, make it
std::atomicand use its operations everywhere. The rule then travels with the variable and cannot be skipped by a new access path. - Third, if several variables share an invariant, or an access is a multi-step sequence, guard every access with one mutex and a scope-bound lock such as
std::lock_guard. - Fourth, set the race exit status explicitly in a test suite instead of assuming a documented default from another build.
- Fifth, treat a clean run as evidence about the paths that ran. Add the workload that exercises the shared state before calling the race gone.
Which fix for which cause
| Cause | Report shape | Fix |
|---|---|---|
| Two writers, no guard | Write vs write | Mutex or atomic |
| Writer and reader, no guard | Write vs read | Mutex or atomic |
| One access skips the lock | Any pair | Same mutex everywhere |
| Group of values, one invariant | Race on one member | One mutex for the group |
| Single counter or flag | Race on that variable | std::atomic |
| Checker aborts at startup | FATAL mapping line | setarch run |
Checklist
- Read the location line first: it names the variable, and every access to that variable is in scope for the fix.
- Read both access blocks: the current access and the
Previousone, with their sizes and frame#0lines. - Check the creation stacks when the access stacks do not show which threads are involved.
- Apply one rule to every access: the same mutex on all paths, or the variable made atomic.
- Reach for a mutex when values must change together; reach for an atomic when one variable acts alone.
- Remember that
mainreturning 0 does not set the exit status when a report was issued: the measured status here is 66. - Run the workload that actually shares the variable. The checker reports only the races that execute.
Related guides on this site
- Fix LeakSanitizer "Detected Memory Leaks" — Direct vs Indirect Leaks, Traced to the Owner — the AddressSanitizer leak checker companion, where the report arrives at exit and each section traces an allocation to the object that should own it.
- Reading an AddressSanitizer Heap-Use-After-Free — Fault, Freed-By, Allocated-By — the lifetime companion, where memory is freed too early and then used, read through its three stacks.
- Fix UBSan "Signed Integer Overflow" Runtime Errors — and Why the Optimizer Cares — the UndefinedBehaviorSanitizer companion, where the report names an arithmetic operation instead of a shared variable.
- Sanitizer Report Decoder — the tool form of this reading: paste a sanitizer report and get its sections and stacks explained.
Sources
- Google, ThreadSanitizerCppManual — for ThreadSanitizer being a data race detector for C and C++, for a data race occurring when two threads access the same variable concurrently and at least one access is a write, for the C++ standard banning data races as undefined behavior, for building and linking with
-fsanitize=thread, for using-gto get file names and line numbers in warning messages, and for the example report form with current and previous access stacks, thread creation stacks, and the closing warnings count. - Google, ThreadSanitizerFlags — for run-time flags being passed through
TSAN_OPTIONS, forexitcodewith default 66 overriding the exit status when something was reported, and forhalt_on_errorwith default 0 exiting after the first reported error. - GCC, Instrumentation Options — for
-fsanitize=threadenabling ThreadSanitizer as a data race detector with run-time behavior influenced throughTSAN_OPTIONS, for the option not being combinable with-fsanitize=addressor-fsanitize=leak, for using-gfor more meaningful output, and for turning address space randomization off withsetarchfor stable sanitizer output. - cppreference, std::mutex — for
std::mutexbeing a synchronization primitive that protects shared data from simultaneous access, for its exclusive ownership semantics fromlocktounlock, and forstd::lock_guardmanaging locking in a scope-based manner. - cppreference, std::atomic — for each
std::atomicinstantiation defining an atomic type, for a write by one thread with a read by another being well-defined on an atomic object, and for read-modify-write operations being one atomic operation rather than several.
Keep Exploring
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.
Paste sshd -G output and get a hardening verdict on the values your server actually runs.
Paste a server block and get WebSocket, TLS, HSTS, and proxy-header verdicts.
Paste a systemd timer expression and get the specific reason it fails, the normalized form, and the past-date traps the built-in check hides.
The full sysadmin hub \u2014 systemd, cgroups, file tools, and measured Linux comparisons.