Linux上C语言的原子操作 [英] Atomic Operations in C on Linux

查看:226
本文介绍了Linux上C语言的原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我从Mac OS X编写的一些代码移植到Linux,并努力寻找适合OSX的替代品 OSAtomic.h 。我发现了gcc __ sync * 系列,但我不确定它是否与旧版编译器/内核兼容。我需要在GCC v4.1.2和2.6.18内核上运行代码。



我需要的特定操作是:


  • 增量

  • 减量

  • 比较和交换


奇怪的是,在linux机器上运行 locate stdatomic.h 找到头文件(在c ++目录下),而在我的OSX机器上运行相同的命令(gcc v4.6.3)不会返回任何结果。我需要安装什么来获取stdatomic库,它会使用gcc v 4.1.2吗?



作为一个方面说明,我不能使用任何第三方党的图书馆。

解决方案

好吧,没有什么能阻止你使用 OSAtomic 操作在其他平台上。 ARM,x86和PPC的 OSAtomic 操作源是Apple开放源码的libc的一部分。只要确保你没有使用 OSSpinLock ,因为它特定于Mac OS X,但这可以很容易地由Linux futex取代。



看到这些:

http://opensource.apple.com/source/Libc/Libc-594.1.4/i386/sys/OSAtomic.s
http://opensource.apple.com/source/Libc/ Libc-594.1.4 / ppc / sys / OSAtomic.s
http://opensource.apple.com/source/Libc/Libc-594.1.4/arm/sys/OSAtomic.s



或者,您可以使用 sync _ * 系列,我相信它可以在大多数平台上工作,我相信这些平台会在这里描述: http://gcc.gnu.org/wiki/Atomic


I am trying to port some code I wrote from Mac OS X to Linux and am struggling to find a suitable replacement for the OSX only OSAtomic.h. I found the gcc __sync* family, but I am not sure it will be compatible with the older compiler/kernel I have. I need the code to run on GCC v4.1.2 and kernel 2.6.18.

The particular operations I need are:

  • Increment
  • Decrement
  • Compare and Swap

What is weird is that running locate stdatomic.h on the linux machine finds the header file (in a c++ directory), whereas running the same command on my OSX machine (gcc v4.6.3) returns nothing. What do I have to install to get the stdatomic library, and will it work with gcc v 4.1.2?

As a side note, I can't use any third party libraries.

解决方案

Well, nothing is there to stop you from using OSAtomic operations on other platforms. The sources for OSAtomic operations for ARM, x86 and PPC are a part of Apple's libc which is opensource. Just make sure you are not using OSSpinLock as that is specific to Mac OS X, but this can be easily replaced by Linux futexes.

See these:

http://opensource.apple.com/source/Libc/Libc-594.1.4/i386/sys/OSAtomic.s http://opensource.apple.com/source/Libc/Libc-594.1.4/ppc/sys/OSAtomic.s http://opensource.apple.com/source/Libc/Libc-594.1.4/arm/sys/OSAtomic.s

Alternatively, you can use the sync_* family, which I believe should work on most platforms, which I believe are described here: http://gcc.gnu.org/wiki/Atomic

这篇关于Linux上C语言的原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆