简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM