← C++ roadmap

Topic 20 of 27 · Expert

Why is a C++ data race more serious than a lost update?

Concurrent conflicting accesses to the same memory, at least one a write, without required synchronization create a data race and undefined behavior. It is not merely an unpredictable final count.

ExpertSenior · 5–8 yearsConcurrency

C++20; compile with g++ -std=c++20.

Detailed answer

Concurrent conflicting accesses to the same memory, at least one a write, without required synchronization create a data race and undefined behavior. It is not merely an unpredictable final count.

Use mutexes for compound invariants and atomics for carefully specified shared values. Memory-order choices require a happens-before argument; start with safe defaults.

Atomic reference counting does not make the pointed-to object thread safe. Avoid unsynchronized publication and use thread sanitizers during testing.

Internal working

The compiler may optimize under the assumption that ordinary data races do not occur. Synchronization establishes visibility and ordering, not just serialization of one instruction.

Practical scenario

Two workers mutate a shared vector. Atomic length counters do not protect reallocations or element initialization.

#include <atomic>
#include <iostream>
int main(){std::atomic<int> n{0};n.fetch_add(1);std::cout<<n.load()<<"\n";}
Common mistakes
  • Using volatile for thread synchronization.
  • Assuming shared_ptr protects the object's fields.
Key takeaways
  • Data races are undefined behavior.
  • Protect invariants, not just counters.
  • Prove ordering before weakening it.
Follow-up challenges
  • When is relaxed ordering sufficient?
  • How would you publish an immutable object safely?
Practise C++ with the AI mentor

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.