How 'undefined' a race condition can be?

前端 未结 7 514
甜味超标
甜味超标 2021-01-03 02:49

Let\'s say I define a following C++ object:

class AClass
{
public:
    AClass() : foo(0) {}
    uint32_t getFoo() { return foo; }
    void changeFoo() { foo          


        
7条回答
  •  耶瑟儿~
    2021-01-03 03:23

    In practice, you will not see anything else than 0 or 5 as far as I know (maybe some weird 16 bits architecture with 32 bits int where this is not the case).

    However whether you actually see 5 at all is not guaranteed.

    Suppose I am the compiler.

    I see:

    while (aObject.getFoo() == 0) {
        printf("Sleeping");
        sleep(1);
    }
    

    I know that:

    • printf cannot change aObject
    • sleep cannot change aObject
    • getFoo does not change aObject (thanks inline definition)

    And therefore I can safely transform the code:

    while (true) {
        printf("Sleeping");
        sleep(1);
    }
    

    Because there is no-one else accessing aObject during this loop, according to the C++ Standard.

    That is what undefined behavior means: blown up expectations.

提交回复
热议问题