difference in mfence and asm volatile (“” : : : “memory”)

前端 未结 3 1701
醉酒成梦
醉酒成梦 2021-01-30 09:12

As far as I have understood, mfence is a hardware memory barrier while asm volatile (\"\" : : : \"memory\") is a compiler barrier. But,can asm vo

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 10:04

    There are two reorderings, one is compiler reordering, the other one is CPU reordering.

    x86/x64 has a relatively strong memory model, but on x86/x64 StoreLoad reordering (later loads passing earlier stores) CAN happen. see http://en.wikipedia.org/wiki/Memory_ordering

    • asm volatile ("" ::: "memory") is just a compiler barrier.
    • asm volatile ("mfence" ::: "memory") is both a compiler barrier and CPU barrier.

    that means, only use a compiler barrier, you can only prevent compiler reordering, but you can not prevent CPU reordering. that means there is no reordering when compiling source code, but reordering can happen in runtime.

    So, it depends your needs, which one to use.

提交回复
热议问题