在 C# 中,有没有类似于 x86 汇编中 xchg
指令的等价物呢?
使用这个指令,我可以原子地交换两个整数(不像 Interlocked.Exchange
),这正是我想要做的。
更新:
基于我的建议,以下是示例代码。带有 "_V" 后缀的变量被标记为易失性:
// 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;
请注意惰性更新。
XCHG [mem1],[mem2]
操作码,所以XCHG
指令不是您要寻找的原子操作。您需要使用三条指令:mov reg,[mem1] XCHG reg,[mem2] mov [mem1],reg
。 - Skizz