3

在 msdn http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208(v=vs.85).aspx上,MemoryBarrier 被实现为对 xchg 的调用。

// x86

FORCEINLINE
VOID
MemoryBarrier (
    VOID
    )
{
    LONG Barrier;
    __asm {
        xchg Barrier, eax
    }
}

我在“软件开发人员手册”中找不到一些资料。请告诉我原因。

4

2 回答 2

4

这里发生了两件事:

  1. 编译器被赋予一个不透明的块以插入到输出指令流中。由于它不知道块内访问了哪些数据,因此它无法重新排序围绕它的其他语句。

  2. xchg指令执行原子读-修改-写操作,这需要在内存总线上进行排序,因此 CPU 会强制执行内存屏障。

于 2013-10-29T08:15:29.537 回答
3

From Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3: "System Programming Guide"

8.2.5 "Strengthening or Weakening the Memory-Ordering Model"

Synchronization mechanisms in multiple-processor systems may depend upon a strong memory-ordering model. Here, a program can use a locking instruction such as the XCHG instruction or the LOCK prefix to ensure that a read-modify-write operation on memory is carried out atomically. Locking operations typically operate like I/O operations in that they wait for all previous instructions to complete and for all buffered writes to drain to memory (see Section 8.1.2, “Bus Locking”).

And from 8.1.2:

Locked operations are atomic with respect to all other memory operations and all externally visible events. Only instruction fetch and page table accesses can pass locked instructions. Locked instructions can be used to synchronize data written by one processor and read by another processor.

For the P6 family processors, locked operations serialize all outstanding load and store operations (that is, wait for them to complete). This rule is also true for the Pentium 4 and Intel Xeon processors, with one exception. Load operations that reference weakly ordered memory types (such as the WC memory type) may not be serialized.

于 2013-10-29T08:19:37.607 回答