Race condition on x86

前端 未结 3 921
耶瑟儿~
耶瑟儿~ 2020-12-05 13:59

Could someone explain this statement:

shared variables
x = 0, y = 0

Core 1       Core 2
x = 1;       y = 1;
r1 = y;      r2 = x;

How is it

3条回答
  •  攒了一身酷
    2020-12-05 14:25

    This is why some say: Threads Considered Harmful

    The problem is that neither thread enforces any ordering between its two statements, because they are not inter-dependent.

    • The compiler knows that x and y are not aliased, and so it is not required to order the operations.

    • The CPU knows that x and y are not aliased, so it may reorder them for speed. A good example of when this happens is when the CPU detects an opportunity for write combining. It may merge one write with another if it can do so without violating its coherency model.

    The mutual dependency looks odd but it's really no different than any other race condition. Directly writing shared-memory-threaded code is quite difficult, and that's why parallel languages and message-passing parallel frameworks have been developed, in order to isolate the parallel hazards to a small kernel and remove the hazards from the applications themselves.

提交回复
热议问题