C++: protecting shared data with std::mutex
A data race occurs when two threads access the same memory at the same time and at least one writes, with no synchronization. In C++ a data race is undefined behaviour, not just a wrong answer. The statement ++counter is a read, an add, and a write, so concurrent increments can be lost.
C++
#include <iostream>
#include <mutex>
#include <thread>
int main() {
int counter = 0;
std::mutex m;
auto work = [&]() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(m);
++counter;
}
};
std::thread a(work);
std::thread b(work);
a.join();
b.join();
std::cout << "counter=" << counter << "\n";
}