Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code not create a race-condition?

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

like image 463
Jens Avatar asked Aug 12 '26 06:08

Jens


2 Answers

It does.

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.

like image 152
Lightness Races in Orbit Avatar answered Aug 14 '26 18:08

Lightness Races in Orbit


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

like image 34
Oblivion Avatar answered Aug 14 '26 18:08

Oblivion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!