MiddleDebuggingCommonNot answered yet
Why is this threaded counter wrong, and how to fix it?
worker() runs on several std::threads and the final counter is too small.
int counter = 0;
void worker() { for (int i = 0; i < 100000; ++i) ++counter; }
// launch worker() on several std::threads, then join them all
Find and fix the bug.
Data race: ++counter is an unsynchronized read-modify-write across threads, which is undefined behavior, so the final value is unpredictable. Fix with std::atomic<int> counter{0} (then ++counter is atomic) or guard the increment with a std::mutex + lock_guard.
- ✗Believing
++is atomic because it is one operator or one instruction - ✗Thinking
volatileprovides thread-safety - ✗Assuming lost updates only slow it down rather than corrupting the result
- →Why is
volatilenot a substitute forstd::atomicin C++? - →When is a
std::mutexpreferable tostd::atomicfor a counter?