multithreading - `xchg` 是否包含 `mfence` 假设没有非时间指令?

标签 multithreading assembly x86 intel memory-barriers

我已经看过 this answerthis answer ,但对于 mfence 的等价或不等价,两者似乎都没有明确和明确的说明。和 xchg在没有非时间指令的假设下。

英特尔 instruction referencexchg提到这条指令对于实现信号量或类似的数据结构用于进程同步很有用,并进一步引用了 Volume 3A 的第 8 章。 .该引用资料说明如下。

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.


mfence文件声称如下。

Performs a serializing operation on all load-from-memory and store-to-memory instructions that were issued prior the MFENCE instruction. This serializing operation guarantees that every load and store instruction that precedes the MFENCE instruction in program order becomes globally visible before any load or store instruction that follows the MFENCE instruction. 1 The MFENCE instruction is ordered with respect to all load and store instructions, other MFENCE instructions, any LFENCE and SFENCE instructions, and any serializing instructions (such as the CPUID instruction). MFENCE does not serialize the instruction stream.



如果我们忽略弱排序的内存类型, xchg(这意味着 lock )是否包含 mfence 对内存排序的所有保证?

最佳答案

假设您没有编写设备驱动程序 (所以所有的内存都是写回,而不是弱序写组合),然后 xchg强如mfence .

NT商店很好。

我确信当前硬件就是这种情况,并且相当肯定的是,所有 future x86 CPU 的手册中的措辞都可以保证这一点。 xchg是一个非常强大的全内存屏障。

嗯,我没有看过预取指令重新排序。这可能与性能有关,甚至可能与奇怪的设备驱动程序情况下的正确性有关(您可能不应该使用可缓存的内存)。

从你的报价:

(P4/Xeon) Load operations that reference weakly ordered memory types (such as the WC memory type) may not be serialized.



这就是 xchg [mem] 的一件事弱于mfence (在 Pentium4 上?可能也在 Sandybridge 系列上)。
mfence确实保证了这一点,这就是 Skylake 必须加强它以修复错误的原因。 ( Are loads and stores the only instructions that gets reordered? ,以及您在 Does lock xchg have the same behavior as mfence? 上链接的答案)

NT 商店由 xchg 序列化/lock ,它只是可能无法序列化的弱排序加载。 您不能从 WB 内存中执行弱排序加载 . movntdqa xmm, [mem]在 WB 内存上仍然是强排序的(并且在当前的实现中,也忽略了 NT 提示而不是做任何事情来减少缓存污染)。

它看起来像 xchg对于 seq-cst 存储,性能优于 mov + mfence在当前的 CPU 上,所以你应该在普通代码中使用它。 (您不能意外地映射 WC 内存;正常的操作系统将始终为您提供 WB 内存用于正常分配。WC 仅用于视频 RAM 或其他设备内存。)

这些保证是根据英特尔微架构的特定系列规定的。如果我们可以为 future 的 Intel 和 AMD CPU 假设一些常见的“基线 x86”保证,那就太好了。

我假设但尚未检​​查 xchg对比 mfence AMD 的情况也是一样。我确定使用 xchg 没有正确性问题作为 seq-cst 存储,因为这就是 gcc 以外的编译器实际所做的。

关于multithreading - `xchg` 是否包含 `mfence` 假设没有非时间指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51975867/

相关文章:

assembly - call *(%rax, %rcx,8) 在循环中是什么意思?为什么RAX和RCX之后要变?

c - 不使用算术运算符执行位除法

performance - 矛盾的 VTune 放大器微架构探索结果

c++ - 多线程代码 : vector<bool> iterators incompatible

python - 如何在Python中的多处理中跨进程共享大型只读字典/列表?

visual-studio - 如何在 Visual Studio 中制作纯汇编项目?

assembly - 将两个x86 32位寄存器存储到128位xmm寄存器中

c# - 使用线程时是否需要锁定 "read only"服务?

c# - 如何使用 Task.WaitAny() 确定哪些任务首先完成?

assembly - 简单 FASM "Hello world!"在 DOS 中断时崩溃