无锁结构的 C++ 原子操作 [英] C++ atomic operations for lock-free structures
问题描述
我正在使用原子(双)比较和交换指令实现无锁机制,例如cmpxchg16b
I'm implementing a lock-free mechanism using atomic (double) compare and swap instructions e.g. cmpxchg16b
我目前正在汇编中编写它,然后将其链接起来.但是,我想知道是否有办法让编译器自动为我执行此操作?例如用原子"包围代码块,让它去弄清楚如何在底层处理器架构中将代码实现为原子指令(或者如果底层架构不支持,则在编译时生成错误)?
I'm currently writing this in assembly and then linking it in. However, I wondered if there was a way of getting the compiler to do this for me automatically? e.g. surround code block with 'atomically' and have it go figure it out how to implement the code as an atomic instruction in the underlying processor architecture (or generate an error at compile time if the underlying arch does not support it)?
附言我知道 gcc 有一些内置函数(至少对于 CAS)
P.S. I know that gcc has some built-ins (at least for CAS)
http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
推荐答案
已经有点答案这里.
C++0x 标准将提供一些 原子数据类型,主要是使用 std::atomic<> 模板的整数和空类型.那篇文章提到了 Boehm 的 atomic_ops 项目,您可以立即下载和使用.
The C++0x standard will provide some atomic datatypes, mainly integer and void types using std::atomic<> template. That article mentions Boehm's atomic_ops project which you can download and use today.
如果没有,您不能在编译器中内联实现您的汇编程序吗?我知道 MSVC 有 __asm 关键字用于内联汇编程序.谷歌说是的,gcc 也可以.
If not, can't you implement your assembler inline in the compiler? I know MSVC has the __asm keyword for inline assembler routines. Google says yes, gcc can do it too.
这篇关于无锁结构的 C++ 原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!