如何在适用于 x86、arm、GCC 和 icc 的 Linux 上执行原子操作? [英] How to perform atomic operations on Linux that work on x86, arm, GCC and icc?
问题描述
今天每个现代操作系统都提供一些原子操作:
Every Modern OS provides today some atomic operations:
- Windows 具有
Interlocked*
API - FreeBSD 有
- Solaris 有
- Mac OS X 有
Linux 有类似的东西吗?
Anything like that for Linux?
- 我需要它在大多数 Linux 支持的平台上工作,包括:x86、x86_64 和 arm.
- 我需要它至少在 GCC 和英特尔编译器上工作.
- 我不需要使用像 glib 或 qt 这样的 3rd par 库.
- 我需要它在 C++ 中工作(不需要 C)
问题:
- GCC 原子内置函数
__sync_*
并非在所有平台 (ARM) 上都受支持,并且不受英特尔编译器的支持. - AFAIK
不应该在用户空间使用,我根本没有成功使用它.另外,我不确定它是否适用于英特尔编译器.
- GCC atomic builtins
__sync_*
are not supported on all platforms (ARM) and are not supported by the Intel compiler. - AFAIK
<asm/atomic.h>
should not be used in user space and I haven't successfully used it at all. Also, I'm not sure if it would work with Intel compiler.
有什么建议吗?
我知道有很多相关的问题,但其中一些指向 __sync*
这对我来说是不可行的(ARM),有些指向 asm/atomic.h
.
I know that there are many related questions but some of them point to __sync*
which is not feasible for me (ARM) and some point to asm/atomic.h
.
也许有一个内联汇编库可以为 GCC 执行此操作(ICC 支持 gcc 汇编)?
Maybe there is an inline assembly library that does this for GCC (ICC supports gcc assembly)?
有一个仅用于添加操作的非常部分的解决方案(允许实现原子计数器但不允许实现需要 CAS 的无锁结构):
There is a very partial solution for add operations only (allows implementing atomic counter but not lock free-structures that require CAS):
如果您使用 libstc++
(英特尔编译器使用 libstdc++
),那么您可以使用 < 中定义的
或 __gnu_cxx::__exchange_and_add
ext/atomicity.h>
.取决于编译器版本.
If you use libstc++
(Intel Compiler uses libstdc++
) then you can use __gnu_cxx::__exchange_and_add
that defined in <ext/atomicity.h>
or <bits/atomicity.h>
. Depends on compiler version.
不过我还是希望看到支持 CAS 的东西.
However I'd still like to see something that supports CAS.
推荐答案
项目正在使用这个:
http://packages.debian.org/source/sid/libatomic-ops
如果你想要简单的操作,比如 CAS,你不能只在内核之外使用特定于 arch 的实现,并在用户空间中使用 autotools/cmake 进行 arch 检查吗?就许可而言,虽然内核是 GPL,但我认为这些操作的内联程序集是由 Intel/AMD 提供的,而不是内核对它们有许可证是有争议的.它们恰好在内核源代码中以一种易于访问的形式出现.
If you want simple operations such as CAS, can't you just just use the arch-specific implementations out of the kernel, and do arch checks in user-space with autotools/cmake? As far as licensing goes, although the kernel is GPL, I think it's arguable that the inline assembly for these operations is provided by Intel/AMD, not that the kernel has a license on them. They just happen to be in an easily accessible form in the kernel source.
这篇关于如何在适用于 x86、arm、GCC 和 icc 的 Linux 上执行原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!