Reputation: 89
My problem is that when reading about threads it came up that if multiple treads accesses a variable a race-condition would happen. My intuition is that my code would create a race-condition for "int a" in this case like this https://en.wikipedia.org/wiki/Race_condition#Example but it does not happen. My question is why is that so?
I have tried to create multiple threads in a array and individually but the race-condition does not happen.
void increment(int& a) {
++a;
}
int main()
{
int a = 0;
std::thread pool[100];
for (auto& t : pool) {
t = std::thread(increment, std::ref(a));
}
for (auto& t : pool) {
t.join();
}
printf("%d", a);
}
I expect that only some threads actually increases "a" and that a race-condition happens, but that is not the case with my code
Upvotes: 2
Views: 609
Reputation: 9
You can add debug message to print the thread number and value of a in increment function. If increment is in order of thread number then there is no race condition.
Also another point: what do you expect in race condition, this piece of just increments the value of a memory location. It is not a database which will result in dead lock condition
Upvotes: 0
Reputation: 7374
This is a perfect example of unlucky undefined behavior.
It just fools with the result you expect, and you never know when and where it will hit you in face.
To prevent it you either have to use atomics or use a mutex
Upvotes: 6
Reputation: 385385
You just haven't witnessed any symptoms of it yet, due to pure chance.
(I expect that creating and storing those threads one at a time is much slower than the increment itself, so by the time you're onto the next thread the increment from the last one is usually done already. But you can't guarantee this, which is a classic race condition.)
You should/must increment a
atomically, or synchronise it with a mutex.
Upvotes: 7