【发布时间】:2011-04-20 19:38:50
【问题描述】:
x86 asm xchg 指令的 C# 等效项是什么(如果有)?
使用该命令,imo 是一个真正的交换(不像Interlocked.Exchange),我可以简单地原子交换两个整数,这是我真正想要做的。
更新:
基于我的建议的示例代码。变量后缀“_V”被修饰为 volatile:
// PART 3 - process links
// prepare the new Producer
address.ProducerNew.WorkMask_V = 0;
// copy the current LinkMask
address.ProducerNew.LinkMask_V = address.Producer.LinkMask_V;
// has another (any) thread indicated it dropped its message link from this thread?
if (this.routerEmptyMask[address.ID] != 0)
{
// allow all other bits to remain on (i.e. turn off now defunct links)
address.ProducerNew.LinkMask_V &= ~this.routerEmptyMask[address.ID];
// reset
this.routerEmptyMask[address.ID] = 0;
}
// PART 4 - swap
address.ProducerNew = Interlocked.Exchange<IPC.Producer>(ref address.Producer, address.ProducerNew);
// PART 5 - lazily include the new links, make a working copy
workMask = address.Producer.LinkMask_V |= address.ProducerNew.WorkMask_V;
注意惰性更新。
【问题讨论】:
-
请使用您在 cmets 中为我的回答提供的其他详细信息更新您的问题。如果其他人知道所有限制条件,这将有助于其他人尝试回答您的问题。 stackoverflow.com/questions/3855671/…
-
XCHG 指令不是您要查找的原子操作,因为没有
XCHG [mem1],[mem2]操作码。你需要三个指令:mov reg,[mem1] XCHG reg,[mem2] mov [mem1],reg -
@Skizz 我又看了一下 ASM 手册 - 你是对的。哇。即使在汇编程序中也无法完成我正在寻找的工作。
-
实际上,在任何语言中,即使是 ASM,都不可能原子地交换两个变量。只能以原子方式将 a 与 b 交换,而非原子地得到 a 作为结果。
-
@GlennSlayden:m68k 有/有双字比较和交换(内存中两个不连续的字对两个寄存器)。 en.wikipedia.org/wiki/Double_compare-and-swap。在现代英特尔上,您可以使用 TSX(事务性内存)来做到这一点。