What is a data race in C++ and how do you prevent it?

A data race is two or more threads reading and writing the same variable at the same time with no lock. It is undefined behavior. Prevent it with:

  • std::mutex and std::lock_guard or std::scoped_lock.
  • std::atomic<T> for simple counters and flags.
  • Not sharing data: give each thread its own data.
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    std::atomic<int> counter{0};
    std::vector<std::thread> threads;
    for (int t = 0; t < 4; t++) {
        threads.emplace_back([&counter] { for (int i = 0; i < 50000; i++) counter++; });
    }
    for (auto& t : threads) t.join();
    std::cout << counter << '\n';
}
Output

200000

Find races with ThreadSanitizer: g++ -fsanitize=thread. See C++ Multithreading.


Learn more about the similar topics:
Tutorials
C++ Lambda Expressions
C++ Move Semantics and the Rule of Five
Modern C++ Features: ranges, optional, variant and format
C++ Multithreading: thread, mutex and async
Exercises & Assignments
Filter and sum numbers with algorithms and ranges
Interview Questions & Answers
What is the Rule of Three, Five and Zero in C++?
What does std::move do in C++?
What are concepts in C++20?
What is perfect forwarding in C++ (std::forward)?
How do lambda captures work in C++?
What is new in C++20?
What is new in C++23?