c++ - InterlockedDecrement 使用 XADD 但 InterlockedIncrement 使用 INC?

标签 c++ windows x86 atomic interlocked

我正在使用 boost C++ 库调试一些代码,该库使用 Windows InterlockedDecrementInterlockedIncrement

在输出的程序集中,InterlockedIncrement 使用 LOCK INC,而 InterlockedDecrement 使用 LOCK XADD

为什么他们不都使用LOCK XADD

(这是在Win 7 64、64位编译和MSVC 11上)

最佳答案

INC 指令的编码较短。您可以使用 LOCK XADD 来实现两者,但代码会占用更多内存空间。一旦它们变成微指令,它们可能是相同的。

现在,为什么不使用LOCK DEC

我的猜测是有问题的代码是这样的:

InterlockedIncrement(&refcount);
...

if (InterlockedDecrement(&refcount) == 0)
    ...

这是引用计数的常见模式。在这种情况下,您不能使用 LOCK DEC,因为 LOCK DEC 不会返回结果值。

// WRONG WRONG WRONG WRONG
InterlockedDecrement(&refcount);
    // <-- another thread might modify refcount here
if (refcount == 0)
    ...

关于c++ - InterlockedDecrement 使用 XADD 但 InterlockedIncrement 使用 INC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25492294/

相关文章:

c++ - 如何在 Windows 上清理命名管道?

c++ - GLFW程序不画三角形

gcc - 汇编指令 : rdtsc

assembly - 为什么 x86 16 位寻址模式没有比例因子,而 32 位版本有?

windows - 如何解决在 Windows 上的 Ubuntu 上更新 polymer-cli 由于 .git : Permission denied 而失败

linux asm x86 产生段错误

c++ - 为什么输出中缺少字母 'D'?

c++:我在我的数组中得到了一个奇怪的值

windows - 在 Windows 中截取屏幕截图的最快方法是什么?

c# - 标题栏的上下文菜单