C 中的原子变量
我想在 C 中使用原子变量。
我在 gcc 中尝试了以下建议的内置函数,但收到了链接错误 对 `_sync_fetch_and_add' 的未定义引用
。
type __sync_fetch_and_add (type *ptr, type value);
type __sync_fetch_and_sub (type *ptr, type value);
type __sync_fetch_and_or (type *ptr, type value);
type __sync_fetch_and_and (type *ptr, type value);
type __sync_fetch_and_xor (type *ptr, type value);
type __sync_fetch_and_nand (type *ptr, type value);
我假设我的架构不支持它们。我想这可能是因为它不是 INTEL,但查看 CPU 信息我发现我有 Intel CPU。
>less /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 26
model name : Intel(R) Xeon(R) CPU X5570 @ 2.93GHz
stepping : 5
cpu MHz : 1600.000
>uname -a
Linux xxxxxx 2.6.24.7-108.el5rt #1 SMP PREEMPT RT
Mon Mar 23 10:58:10 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
您是否知道可能为我的架构实现原子变量的其他方法或库,或者我是否做错了什么(也许我应该检查一些编译标志)?
注意:我找到了 stdatomic.h
但不幸的是仅适用于 C++
用法示例:
int i =0;
i = _sync_fetch_and_add (&i,2);
I would like to use atomic variables in C.
I tried the following suggested builtin functions in gcc but I received a link error undefined reference to `_sync_fetch_and_add'
.
type __sync_fetch_and_add (type *ptr, type value);
type __sync_fetch_and_sub (type *ptr, type value);
type __sync_fetch_and_or (type *ptr, type value);
type __sync_fetch_and_and (type *ptr, type value);
type __sync_fetch_and_xor (type *ptr, type value);
type __sync_fetch_and_nand (type *ptr, type value);
I am assuming that my architecture doesn't support them..I thought that probably because it is not INTEL but looking a the CPU info I discovered that I have Intel CPU.
>less /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 26
model name : Intel(R) Xeon(R) CPU X5570 @ 2.93GHz
stepping : 5
cpu MHz : 1600.000
>uname -a
Linux xxxxxx 2.6.24.7-108.el5rt #1 SMP PREEMPT RT
Mon Mar 23 10:58:10 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
Do you know other ways or libraries that might implement atomic variables for my architecture or if am I doing something wrong( maybe some compilation flags that I hould check out )?
NOTE: I found stdatomic.h
but is for C++ only unfortunately
Usage example:
int i =0;
i = _sync_fetch_and_add (&i,2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个答案将在 201X 年变得有意义。 :-)
即将推出的 C1X 标准将引入原子作为 C 语言功能。
请参阅C1X 标准草案。
This answer is going to become relevant in the year 201X. :-)
The upcoming C1X standard is to introduce atomics as a C language feature.
See the draft C1X standard.
尝试使用 -march 命令行选项,原子内置函数并非适用于所有目标体系结构。 另请参阅
Try the -march command line option, the atomic builtins are not available for all target architectures. See also