Do we need mfence when using xchg

2019-02-12 18:53发布

I have a set and test xchg based assembly lock. my question is :

Do we need to use memory fencing (mfence, sfence or lfence ) when using xchg instruction ?

Edit :

64 Bit platform : with Intel nehalem

4条回答
时光不老,我们不散
2楼-- · 2019-02-12 19:49

No. xchg is guaranteed to compile into something, that will assure consistency on the hardware level.

查看更多
地球回转人心会变
3楼-- · 2019-02-12 19:50

As said in the other answers the lock prefix is implicit, here, so there is no problem on the assembler level. The problem may lay on the C (or C++) level when you use that as inline assembler. Here you have to ensure that the compiler doesn't reorder instructions with respect to your xchg. If you are using gcc (or cousins) you would typically do something like:

  __asm__ __volatile__("xchgl %1, %0"
                       : "=r"(ret)
                       : "m"(*point), "0"(ret)
                       : "memory");

that is declare the instruction as volatile and add the "memory" clobber.

查看更多
疯言疯语
4楼-- · 2019-02-12 19:50

According to Chapter 8 Bus Locking, of the Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A

The memory-ordering model prevents loads and stores from being reordered with locked instructions that execute earlier or later.

So the locked XCHG instruction acts as a memory barrier, and no additional barrier is needed.

查看更多
干净又极端
5楼-- · 2019-02-12 19:50

xchg instruction has an implicit lock prefix according to Intel manuals.

查看更多
登录 后发表回答