Thread Synchronisation 101

前端 未结 6 485
深忆病人
深忆病人 2021-02-01 06:55

Previously I\'ve written some very simple multithreaded code, and I\'ve always been aware that at any time there could be a context switch right in the middle of what I\'m doing

6条回答
  •  醉酒成梦
    2021-02-01 07:17

    Volatile does not imply memory barriers.

    It only means that it will be part of the perceived state of the memory model. The implication of this is that the compiler cannot optimize the variable away, nor can it perform operations on the variable only in CPU registers (it will actually load and store to memory).

    As there are no memory barriers implied, the compiler can reorder instructions at will. The only guarantee is that the order in which different volatile variables are read/write will be the same as in the code:

    void test() 
    {
        volatile int a;
        volatile int b;
        int c;
    
        c = 1;
        a = 5;
        b = 3;
    }
    

    With the code above (assuming that c is not optimized away) the update to c can happen before or after the updates to a and b, providing 3 possible outcomes. The a and b updates are guaranteed to be performed in order. c can be optimized away easily by any compiler. With enough information, the compiler can even optimize away a and b (if it can be proven that no other threads read the variables and that they are not bound to a hardware array (so in this case, they can in fact be removed). Note that the standard does not require an specific behavior, but rather a perceivable state with the as-if rule.

提交回复
热议问题