Quick Answer
Thread synchronization and data sharing.
Understanding the Issue
C++11+ provides <thread>, <mutex>, and <atomic> for safe concurrency. Prefer higher-level abstractions over raw threads.
The Problem
This code demonstrates the issue:
Cpp
Error
// Problem: Data race
int counter = 0;
auto incr = [&]{ counter++; };
thread t1(incr), t2(incr); // Undefined
The Solution
Here's the corrected code:
Cpp
Fixed
// Solution: Atomic operations
atomic<int> counter{0};
auto safe_incr = [&]{ counter++; };
// Alternative: Mutex
mutex m;
auto locked_incr = [&]{
lock_guard<mutex> lock(m);
counter++;
};
Key Takeaways
Minimize shared mutable state.