I have written this piece of code as test:
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
auto inc(int a) {
for (int k = 0; k < a; ++k)
++counter;
}
int main() {
auto a = std::thread{ inc, 100000 };
auto b = std::thread{ inc, 100000 };
a.join();
b.join();
std::cout << counter;
return 0;
}
The counter
variable is global and so, creating 2 threads a
and b
, I'd expect to find a data race. The output is 200000 and not a random number. Why?
This code is a fixed version that uses a mutex
so that the global variable can be accessed only once (1 thread per time). The result is still 200000 .
std::mutex mutex;
auto inc(int a) {
mutex.lock();
for (int k = 0; k < a; ++k)
++counter;
mutex.unlock();
}
The fact is this. The mutex-solution gives me 200000 which is correct because only 1 threat at time can access counter. But why the non-mutex-solution still shows 200000?