Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 171 ยท Concurrency

Race Conditions and Data Races

Understand the difference between data races and race conditions in C++, see check-then-act, split-invariant and lazy-init bugs reproduced on demand, and fix them with locks, CAS and call_once.

Two words come up whenever threads share data, and people use them as if they meant the same thing. They don't. A data race is a precise, language-level definition: two threads touch the same memory location without synchronization and at least one of them writes. In C++ that is undefined behavior. A race condition is a bug in your program's logic: the result depends on how the threads happen to interleave. You can have either one without the other, and removing data races does not remove race conditions.

This lesson makes both visible. You'll learn why a program with no data race can still be wrong, then reproduce three classic race conditions deterministically (a normal race happens one run in a thousand; we use std::barrier to force the bad interleaving every time so you can study it). Along the way you'll see the fixes: a lock around the whole operation, a compare-and-swap loop, and std::call_once. It builds on Threads, Mutexes and Locks and Atomics.

Data race versus race condition

Here is the difference in one table.

Data race Race condition
What it is Unsynchronized conflicting access to one memory location A logic bug that depends on timing
In C++ Undefined behavior Defined behavior, wrong outcome
Removed by A mutex or an atomic variable Making the whole operation indivisible, or redesigning it
Found by ThreadSanitizer Reasoning, stress tests, review

A program that increments a plain int from two threads has a data race. A program that checks an atomic balance and then subtracts from it has no data race at all (every access is atomic), yet it still has a race condition, as the first example shows.

The reason the second kind survives is that locks and atomics protect single accesses, while your program's correctness depends on sequences of accesses. "Read the balance, decide, then write the balance" is three steps, and another thread can slip between any two of them.

Check-then-act on an atomic

Our bank account keeps its balance in a std::atomic<int>, so every individual read and write is safe. Two threads each try to withdraw 80 from an account holding 100, so at most one should succeed. To make the race happen every time, a std::barrier makes both threads finish their check before either one acts.

C++ Atomic, race-free, and still wrong

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.

Both withdrawals succeed and the balance ends at -60. There is no data race here: every access to balance is atomic, and ThreadSanitizer would stay silent. The bug is that the check and the act are two separate atomic operations, and the world changed in between. The barrier is only there to make the bad schedule certain. Without it the bug appears rarely, on a busy machine, in production, which is the worst possible time.

There are two ways to fix a check-then-act. For a single variable, use compare-and-swap: tell the hardware "subtract 80, but only if the balance is still what I saw."

C++ Fixing check-then-act with compare_exchange

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.

Now exactly one withdrawal succeeds and the balance is 20. Whichever thread loses the swap sees the new balance (20), fails the seen >= amount test, and gives up. The same pattern fits any "update one atomic based on its previous value" operation. When the operation involves more than one variable, a CAS is no longer enough, and you need a lock, which is the next example.

One invariant, several variables

An invariant is a rule about your data that must hold whenever another thread can look. "The total money in the bank never changes" is an invariant spanning two accounts. If each account has its own lock, every access is race-free, but a transfer still has a moment in the middle where the money has left one account and not yet reached the other.

C++ Split invariant: money disappears mid-transfer

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 auditor reports 800. Every add and balance call is properly locked, so there is no data race, yet the program is wrong because the transfer was not one indivisible operation. The fix is to widen the critical section so both accounts change under the same protection. std::scoped_lock can lock two mutexes at once without deadlock (see Deadlock and std::scoped_lock).

C++
void transfer(Account& from, Account& to, int amount) {
    std::scoped_lock lock{from.mutex_, to.mutex_};   // both locked together
    from.balance_ -= amount;
    to.balance_ += amount;
}

(That function needs access to the private members, so in a real class it would be a member or a friend, and the auditor would lock both accounts the same way before summing.) The general rule: a lock must cover the whole read-modify-write sequence that your invariant depends on, never just each variable's individual access. If two things must change together, give them one mutex, ideally inside one class that exposes only whole operations such as transfer and total.

Lazy initialization races

A third classic is creating something "the first time it's needed." The obvious code checks a pointer and builds the object if it's still null. That is both a data race and a race condition: two threads can both see null and both build.

C++ Two threads both initialize the singleton

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 naive version builds two Config objects (and leaks one: see Memory Leaks); the call_once version builds exactly one. In everyday code you rarely write either: a function-local static variable (static Config config; inside a function) is initialized exactly once, thread-safely, since C++11. Reach for std::call_once when the initialization needs runtime arguments or can fail and be retried.

Avoid the famous "double-checked locking" trick with a plain pointer or bool. Reading that variable without a lock while another thread writes it is a data race, and the compiler or CPU may let a thread see the pointer before the object it points to is fully built. Use call_once, a function-local static, or an atomic with the right memory ordering.

Other races worth recognizing

  • The unsynchronized flag. bool done = false; set by one thread and polled by another is a data race, and the compiler is allowed to hoist the read out of the loop so the poller never stops. Use std::atomic<bool> or a std::stop_token.
  • Iterating while another thread modifies. Pushing to a std::vector while another thread loops over it can invalidate iterators and reallocate under the reader's feet. Containers are not thread-safe for concurrent writes, and reads concurrent with writes.
  • File system and external state. if (!exists(path)) create(path) races with any other process (see Filesystem). Prefer one operation that does both, and handle the error.
  • Order of side effects. Two threads printing with std::cout do not corrupt memory, but their output interleaves in arbitrary order. If order matters, it must be synchronized.

Preventing and finding races

Races are hard to find by testing because they depend on timing. A habit that works better than hunting is to design them out.

  1. Don't share. Give each thread its own data and combine results at the end, for example with futures (see Async and Futures).
  2. Share immutable data. Data that never changes needs no lock. Mark it const and build it before starting threads.
  3. Pass messages. Hand data to another thread through a queue protected by a mutex and condition variable (see Condition Variables) and stop touching it yourself.
  4. Keep locks with data. Put the mutex next to the data it guards in the same class, and expose whole operations rather than getters and setters.

When you cannot avoid sharing, test aggressively. Build a separate binary with ThreadSanitizer, which instruments every memory access and reports data races even when the output was correct this time. The command is g++ -std=c++23 -g -O1 -fsanitize=thread main.cpp -o app, and the report names both conflicting accesses with stack traces. It cannot see race conditions like the atomic balance, because no memory rule was broken, so pair it with stress tests: run the operation from many threads thousands of times, check the invariant at the end, and use barriers or latches like the ones above to force the awkward interleavings. See Sanitizers and Valgrind for TSan in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement best describes a data race in C++?

    A data race is the precise language-level definition of unsynchronized conflicting access. A timing-dependent logic bug is a race condition, and threads waiting on each other is a deadlock.
  2. 2. Both threads in the atomic-balance example read balance.load() and then call fetch_sub(80). Why can the balance still go negative?

    Each operation is atomic, but the sequence is not. This is a race condition rather than a data race. A compare-exchange loop or a lock around the whole operation fixes it.
  3. 3. Two accounts each have their own mutex, and a transfer locks them one at a time. What can an auditor thread observe?

    Each access is locked, so there is no data race, but the invariant spans both accounts. The transfer must hold both locks together, for example with std::scoped_lock.
  4. 4. Which is the simplest correct way to create a global object exactly once in a multithreaded program?

    C++ guarantees that a function-local static is initialized once, thread-safely. std::call_once does the same for initialization that needs runtime arguments or retries.
  5. 5. ThreadSanitizer reports nothing for a program. What can you conclude?

    TSan only reports unsynchronized memory accesses it actually saw. A check-then-act bug on atomics breaks no memory rule, so it passes; stress tests and careful design are still needed.

Summary

  • A data race is unsynchronized conflicting access to one memory location (undefined behavior). A race condition is a timing-dependent logic bug. Fixing one does not fix the other.
  • Locks and atomics protect single accesses; correctness usually depends on whole sequences, so the lock or atomic operation must cover the entire check-then-act or read-modify-write.
  • For one atomic variable, use a compare_exchange loop. For invariants over several variables, put them under one mutex (std::scoped_lock for several).
  • Initialize shared objects once with a function-local static or std::call_once; avoid hand-rolled double-checked locking.
  • Prefer designs without sharing: thread-local data, immutable data, message passing, and mutexes kept next to the data they guard.
  • Use ThreadSanitizer for data races, and std::barrier/std::latch stress tests to force the interleavings that cause race conditions.

Next: Condition Variables, where threads wait for something to happen instead of polling for it.