Why volatile and MemoryBarrier do not prevent operations reordering?

后端 未结 4 1253
耶瑟儿~
耶瑟儿~ 2021-02-05 17:10

If I understand meaning of volatile and MemoryBarrier correctly than the program below has never to be able to show any result.

It catches reordering of write operations

4条回答
  •  再見小時候
    2021-02-05 17:44

    I don't think this is re-ordering.

    This piece of code is simply not thread-safe:

     while (continueChecking)
     {
         int tempA = a;
         int tempB = b;
         ...
    

    I think this scenario is possible:

    1. int tempA = a; executes with the values of the last loop (a == 2)
    2. There is a context switch to the Write thread
    3. b = 10 and the loop stops
    4. There is a context switch to the Check thread
    5. int tempB = b; executes with b == 10

    I notice that the calls to MemoryBarrier() enhance the chances of this scenario. Probably because they cause more context-switching.

提交回复
热议问题