C , C++ unsynchronized threads returning a strange result

后端 未结 4 1480
执念已碎
执念已碎 2020-12-07 02:54

Okay, i have this question in one regarding threads.

there are two unsynchronized threads running simultaneously and using a global resource \"int num\" 1st:

4条回答
  •  感动是毒
    2020-12-07 03:20

    num++ and num-- don't have to be atomic operations. To take num++ as an example, this is probably implemented like:

    int tmp = num;
    tmp = tmp + 1;
    num = tmp;
    

    where tmp is held in a CPU register.

    Now let's say that num == 0, both threads try to execute num++, and the operations are interleaved as follows:

    Thread A        Thread B
    int tmp = num;
    tmp = tmp + 1;
                    int tmp = num;
                    tmp = tmp + 1;
    num = tmp;
                    num = tmp;
    

    The result at the end will be num == 1 even though it should have been incremented twice. Here, one increment is lost; in the same way, a decrement could be lost as well.

    In pathological cases, all increments of one thread could be lost, resulting in num == -100000000, or all decrements of one thread could be lost, resulting in num == +100000000. There may even be more extreme scenarios lurking out there.

    Then there's also other business going on, because num isn't declared as volatile. Both threads will therefore assume that the value of num doesn't change, unless they are the one changing it. This allows the compiler to optimize away the entire for loop, if it feels so inclined!

提交回复
热议问题