Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

Data races in C++

What a data race is in C++, why it is undefined behavior, and how atomics, mutexes, per-thread data and ThreadSanitizer help you avoid and find them.

A data race happens when two threads access the same memory location at the same time, at least one access is a write, and nothing orders the accesses (no mutex, atomic or other synchronization). In C++ a data race is undefined behavior: not just a wrong number, but anything, including lost updates, torn values, or an optimizer rewriting your code under the assumption that no race exists.

A race is not the same as a race condition. A data race is a precise rule violation about memory accesses; a race condition is a logic bug where the result depends on timing, and you can have one without the other (for example two properly locked threads that check-then-act on separate lock acquisitions).

C++
int counter = 0;
// thread 1: ++counter;   thread 2: ++counter;   -> data race (undefined behavior)
std::atomic<int> safe = 0;
// thread 1: ++safe;      thread 2: ++safe;      -> well defined

Try it

C++ Three race-free counters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ A check-then-act race condition, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The racy version is deliberately not run here, because its output is unstable and the behavior is undefined. This is what it looks like, read-only:

C++
int counter = 0;                        // plain int, shared
auto work = [&] { for (int i = 0; i < 100000; ++i) ++counter; };
std::thread a(work), b(work);           // both write counter: DATA RACE
a.join(); b.join();
// may print any number up to 200000; the compiler may also assume
// "nobody else touches counter" and keep it in a register

Syntax

There is no single syntax; avoidance rests on these tools:

C++
std::atomic<T> x;                        // indivisible reads/writes/RMW operations
std::mutex m; std::lock_guard g(m);      // mutual exclusion
std::thread::join();                     // joining orders everything the thread did before the join
Tool Description
std::atomic<T> Concurrent access to an atomic object is never a data race. The default memory_order_seq_cst is the safest.
std::mutex and guards Everything done while holding the lock is ordered with the next holder of the same lock.
join(), future::get(), latch, condition_variable Create "happens-before" edges between threads.
thread_local Gives each thread its own copy, so nothing is shared.
ThreadSanitizer Build with -fsanitize=thread -g; reports races at run time. Not available on our runner.

Errors / undefined behavior: any data race is undefined behavior, even a "harmless" one such as two threads writing the same value, or reading a flag that another thread sets.

Usage notes

  • Reads alone are safe. Many threads may read an object that nobody writes, for example a const vector filled before the threads started.
  • volatile is not synchronization. Unlike in some other languages, it does not prevent data races in C++. Use std::atomic.
  • Different elements are different locations. Threads writing v[0] and v[1] of a std::vector<int> do not race, but resizing the vector (push_back) while others access it does. Adjacent elements can share a cache line (false sharing), which is slow but still correct.
  • std::vector<bool> is the exception: neighbouring elements share bits, so writing two elements from two threads is a race.
  • Standard containers give no thread safety beyond "const operations may run concurrently". Protect a container that is modified.
  • Prefer less sharing: give each thread its own data and combine the results after join(). It is faster and simpler than locking.
  • Local variables captured by reference are shared with the thread that runs the lambda. Capture by value when the thread should have its own copy, and keep the referenced object alive until the thread is joined.
  • Test with sanitizers. A race that passes a thousand runs can still be there. Run tests under ThreadSanitizer on a machine that has it.
  • Check-then-act (test a condition, then act on it in a separate critical section) is a race condition even if each step is locked. Keep the check and the action under one lock.