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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.