有人可以验证以下用于比较和设置的内联汇编代码 gcc 的正确性吗?
在我看来,该功能运行良好。我正在尝试为多线程应用程序实现一个计数器。由于计数器值可能超出整数范围,因此我使用 64 位。我不太确定线程安全性,因为这里我们处理的是 64 位数字。
UINT64 get_and_increment(volatile UINT64* dest) {
UINT64 old_value, new_value;
bool result = false;
while(!result) {
old_value = *dest;
new_value = old_value + 1;
__asm__ volatile (
"lock cmpxchg %3, %1 \n setzb %0"
: "=m"(result), "+m" (*dest)
: "a" (old_value), "r"(new_value)
);
}
return old_value;
}
感
谢苏丹舒克拉
The function as it looks to me is working fine. I am trying to implement a counter for a multi threaded application. As the counter value can be beyond the integer range, I using 64 bit for it. I am not very sure about the thread safety as, here we are dealing with 64 bit numbers.
UINT64 get_and_increment(volatile UINT64* dest) {
UINT64 old_value, new_value;
bool result = false;
while(!result) {
old_value = *dest;
new_value = old_value + 1;
__asm__ volatile (
"lock cmpxchg %3, %1 \n setzb %0"
: "=m"(result), "+m" (*dest)
: "a" (old_value), "r"(new_value)
);
}
return old_value;
}
Thanks
Sudhanshu Shukla
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不使用GCC 内置的原子内在函数?
或者甚至
话虽如此,您的程序集无法在 32 位平台上运行(缺少 64 位
lock cmpxchg
),并且可以更简单地编写为lock xadd
没有循环,但看起来它可以在 64 位上运行。Why not use GCC's built-in atomic intrinsics?
Or even
That being said, your assembly won't work on 32-bit platforms (lack of a 64-bit
lock cmpxchg
), and would be simpler written aslock xadd
without a loop, but otherwise looks like it would work on 64-bit.