Linux – Atomic Operations in C on Linux

atomiccgcclinux

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.

Best Answer

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