SFENCE、LFENCE、MFENCE指令

来源:互联网 发布:团队介绍网页源码 编辑:程序博客网 时间:2024/05/19 19:44

                                                                     SFENCE、LFENCE、MFENCE指令

        当系统在做Memory IO操作的时候,用Index和Data间接方式访问寄存器(比如APIC 寄存器),这个时候需要加入写延时,否则,数据就会错位,因为系统硬件做流水操作,导致程序不能严格的顺序执行。而以前的延时值都是自己在实际中进行测试,选择一个比较合适的值,比较笨的方法!后来同事发现了mfence这个指令,可以正好使用在这个地方。mfence保证系统在后面的memory访问之前,先前的memory访问都已经结束。这是mfence是X86cpu家族中的新指令。


SFENCE,LFENCE,MFENCE指令提供了高效的方式来保证读写内存的排序,这种操作发生在产生弱排序数据的程序和读取这个数据的程序之间。 
   SFENCE——串行化发生在SFENCE指令之前的写操作但是不影响读操作。 
   LFENCE——串行化发生在SFENCE指令之前的读操作但是不影响写操作。 
   MFENCE——串行化发生在MFENCE指令之前的读写操作。
sfence:在sfence指令前的写操作当必须在sfence指令后的写操作前完成。
lfence:在lfence指令前的读操作当必须在lfence指令后的读操作前完成。
mfence:在mfence指令前的读写操作当必须在mfence指令后的读写操作前完成。

注意:SFENCE,LFENCE,MFENCE指令提供了比CPUID指令更灵活有效的控制内存排序的方式。

mfence is a memory barrier supported by hardware, and it only makes sense for shared memory systems.

For example, you have the following codes
<codes1>
mfence
<codes2>

mfence or other memory barriers techniques disallows the code motion (load/store)from codes2 to codes1 done by _hardware_ . Some machines like P4 can move loads in codes 2 before stores in codes1, which is out-of-order.

Another memory barrier is something like ("":::"memory"), which disallows the code motion done by _compiler_. But IMO memory access order is not always guaranteed in this case.
原创粉丝点击