Could a C++ implementation, in theory, parallelise the evaluation of two function arguments?

后端 未结 4 1833
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 14:14

Given the following function call:

f(g(), h())

since the order of evaluation of function arguments is unspecified (still the case in C++11

4条回答
  •  梦毁少年i
    2020-12-23 15:11

    Easy answer: when the functions are sequenced, even if indeterminately, there is no possibility for a race condition between the two, which is not true if they are parallelized. Even a pair of one line "trivial" functions could do it.

    void g()
    {
        *p = *p + 1;
    }
    
    
    void h()
    {
        *p = *p - 1;
    }
    

    If p is a name shared by g and h, then a sequential calling of g and h in any order will result in the value pointed to by p not changing. If they are parallelized, the reading of *p and the assigning of it could be interleaved arbitrarily between the two:

    1. g reads *p and finds the value 1.
    2. f reads *p and also finds the value 1.
    3. g writes 2 to *p.
    4. f, still using the value 1 it read before will write 0 to *p.

    Thus, the behavior is different when they are parallelized.

提交回复
热议问题