简体   繁体   English

使用xchg时我们需要mfence吗?

[英]Do we need mfence when using xchg

I have a set and test xchg based assembly lock. 我有一套基于测试xchg的装配锁。 my question is : 我的问题是:

Do we need to use memory fencing ( mfence , sfence or lfence ) when using xchg instruction ? 使用xchg指令时是否需要使用内存防护( mfencesfencelfence )?

Edit : 编辑:

64 Bit platform : with Intel nehalem 64位平台:采用Intel nehalem

According to Chapter 8 Bus Locking , of the Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3A 根据英特尔64和IA-32架构软件开发人员手册第3A卷第8章总线锁定

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. 因此,锁定的XCHG指令充当内存屏障,不需要额外的屏障。

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. 当您将其用作内联汇编程序时,问题可能在于C(或C ++)级别。 Here you have to ensure that the compiler doesn't reorder instructions with respect to your xchg . 在这里,您必须确保编译器不会重新排序与xchg指令。 If you are using gcc (or cousins) you would typically do something like: 如果您使用gcc(或表兄弟),您通常会执行以下操作:

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

that is declare the instruction as volatile and add the "memory" clobber. 这是将指令声明为volatile 添加“memory”clobber。

不, xchg保证可以编译成某种东西,这将确保硬件级别的一致性。

根据Intel手册,xchg指令具有隐式锁定前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM