我正在使用原子(双)比较和交换指令实现无锁机制,例如 cmpxchg16b
我目前正在汇编中编写此内容,然后将其链接到其中。但是,我想知道是否有一种方法可以让编译器执行此操作自动为我? 例如,用“原子”包围代码块,并让它弄清楚如何在底层处理器架构中将代码实现为原子指令(或者如果底层架构不支持,则在编译时生成错误)?
PS 我知道 gcc 有一些内置函数(至少对于 CAS 来说)
http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins
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)?
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
发布评论
评论(2)
C++ 的未来“C++0x”标准将支持原子操作 &c ——参见 http://www.open-std.org/JTC1/sc22/wg21/docs/papers/2007/n2427.html 进行相当彻底的讨论。 当然,在即将推出的标准获得批准并广泛实施之前,无法跨编译器“移植”此类功能; 如果您对 gcc 之外的特定编译器感兴趣,也许您可以专门针对它们提出另一个问题。
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.html for 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++0x 标准将提供一些 原子数据类型,主要是使用 std::atomic<> 的整数和 void 类型 模板。 该文章提到了 Boehm 的atomic_ops 项目,您现在就可以下载并使用它。
如果没有,您不能在编译器中内联实现汇编器吗? 我知道 MSVC 有 __asm 内联关键字汇编程序例程。 Google 说是,gcc 也可以做到。
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 project which you can download and use today.
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.