gpt4 book ai didi

c++ - 对不同的整数宽度使用 xadd

转载 作者:行者123 更新时间:2023-11-30 04:36:02 37 4
gpt4 key购买 nike

我目前正在为一个项目从 boost 中移植 atomic.hpp,并希望概括原子添加函数,从而将其模板化为要添加的类型:

template <typename T, typename V>
inline T add(volatile T* mem, V val)
{
T r;

asm volatile
(
"lock\n\t"
"xadd %1, %0":
"+m"( *mem ), "=r"( r ):
"1"( val ):
"memory", "cc"
);

return r;
}

我找不到明确的文档说明可以安全地使用有符号和无符号的 8、16、32 和 64 位数字。有人知道吗?

最佳答案

是的,您可以在 IA32 或 IA64 下对所有类型的 8、16、32 和 64 位有符号或无符号数字使用 lock xadd。不需要内存对齐,但如果需要,则内存访问速度更快。

来自英特尔手册:

The integrity of the LOCK prefix is not affected by the alignment of the memory field. Memory locking is observed for arbitrarily misaligned fields. This instruction’s operation is the same in non-64-bit modes and 64-bit mode.

警告!:

If the LOCK prefix is used with XADD instruction and the source operand is a memory operand, an undefined opcode exception (#UD) may be generated.

所以源操作数必须是寄存器,目的操作数是内存地址!

关于c++ - 对不同的整数宽度使用 xadd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808812/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com