Why volatile and MemoryBarrier do not prevent operations reordering?

后端 未结 4 1249
耶瑟儿~
耶瑟儿~ 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

    The result has nothing to do with reordering, with memory barries, or with volatile. All these constructs are needed to avoid effects of compiler or CPU reordering of the instructions.

    But this program would produce the same result even assuming fully consistent single-CPU memory model and no compiler optimization.

    First of all, notice that there will be multiple Write() tasks started in parallel. They are running sequentially due to lock() inside Write(), but a signle Check() method can read a and b produced by different instances of Write() tasks.

    Because Check() function has no synchronization with Write function - it can read a and b at two arbitrary and different moments. There is nothing in your code that prevents Check() from reading a produced by previous Write() at one moment and then reading b produced by following Write() at another moment. First of all you need synchronization (lock) in Check() and then you might (but probably not in this case) need memory barriers and volatile to fight with memory model problems.

    This is all you need:

            int tempA, tempB;
            lock (locker)
            {
                tempA = a;
                tempB = b;
            }
    

提交回复
热议问题