无锁结构的 C++ 原子操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/930897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ atomic operations for lock-free structures
提问by bugmenot77
I'm implementing a lock-free mechanism using atomic (double) compare and swap instructions e.g. cmpxchg16b
我正在使用原子(双)比较和交换指令实现无锁机制,例如 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)?
我目前正在汇编中编写它,然后将其链接起来。但是,我想知道是否有办法让编译器自动为我执行此操作?例如,用“原子地”包围代码块并让它弄清楚如何在底层处理器架构中将代码实现为原子指令(或者如果底层架构不支持,则在编译时生成错误)?
P.S. I know that gcc has some built-ins (at least for CAS)
PS 我知道 gcc 有一些内置的(至少对于 CAS)
http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
采纳答案by gbjbaanb
Already kindof answered here.
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 projectwhich you can download and use today.
C++0x 标准将提供一些原子数据类型,主要是使用 std::atomic<> 模板的整数和空类型。那篇文章提到了Boehm 的 atomic_ops 项目,您可以立即下载并使用该项目。
If not, can't you implement your assembler inline in the compiler? I know MSVC has the __asmkeyword for inline assembler routines. Google says yes, gcc can do it too.
如果没有,您不能在编译器中内联实现您的汇编程序吗?我知道 MSVC 具有用于内联汇编程序例程的__asm关键字。谷歌说是的,gcc也能做到。
回答by Alex Martelli
The future "C++0x" standard for C++ will support atomic operations &c -- see e.g. http://www.open-std.org/JTC1/sc22/wg21/docs/papers/2007/n2427.htmlfor a reasonably thorought discussion. Until said forthcoming standard is approved and widely implemented, of course, there's no way to get such functionality "portably" across compilers; if you're interested in specific compilers beyond gcc, maybe you can open another question specifically about them.
C++ 的未来“C++0x”标准将支持原子操作 &c——参见例如http://www.open-std.org/JTC1/sc22/wg21/docs/papers/2007/n2427.html以获得合理的彻底的讨论。在上述即将推出的标准获得批准和广泛实施之前,当然,没有办法在编译器之间“可移植地”获得这样的功能;如果您对 gcc 以外的特定编译器感兴趣,也许您可以专门针对它们提出另一个问题。