vendredi 23 août 2019

Why does not this code 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

Aucun commentaire:

Enregistrer un commentaire