Atomic operations in C on Linux

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

I need specific operations:

  • Increment
  • Decrease
  • Comparison and Swap

Which is strange: running locate stdatomic.hon a linux machine finds the header file (in the C ++ directory), while executing the same command on my OSX machine (gcc v4.6.3) returns nothing. What do I need to install in order to get the stdatomic library, and will it work with gcc v 4.1.2?

As a side note, I cannot use third-party libraries.

+5
source share
3 answers

Well, nothing prevents you from using operations OSAtomicon other platforms. Sources for operations OSAtomicfor ARM, x86, and PPC are part of Apple libc, which is open source. Just make sure you are not using OSSpinLock, as is typical for Mac OS X, but it can easily be replaced with Linux futexes.

See the following:

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

+5

OpenPA MIT. , , .

#include "opa_primitives.h"

OPA_int_t my_atomic_int = OPA_INT_T_INITIALIZER(0);

/* increment */
OPA_incr_int(&my_atomic_int);

/* decrement */
OPA_decr_int(&my_atomic_int);

/* compare and swap */
old = OPA_cas_int(&my_atomic_int, expected, new);

(.. , /), .

, , .

+5

GCC GCC 4.0.1.

There is nothing to stop you from creating GCC 4.7 or Clang with GCC 4.1.2, and then getting all the new features like C11 atomics .

There are many places where you can find BSD licensed assembler atomic implementations as a last resort.

+4
source

All Articles