Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic Operations in C on Linux

Tags:

c

linux

gcc

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.

like image 520
charliehorse55 Avatar asked Aug 23 '12 01:08

charliehorse55


People also ask

What are atomic operations in Linux?

The Linux kernel uses a large variety of "atomic" operations — operations that are indivisible as observed from anywhere within the system — to provide safe and efficient behavior in a multi-threaded environment.

What are atomic operations in C?

Atomic operations are sequences of instructions that guarantee atomic accesses and updates of shared single word variables. This means that atomic operations cannot protect accesses to complex data structures in the way that locks can, but they provide a very efficient way of serializing access to a single word.

What are atomic operations in Unix?

Atomic operations are operations like "increment and get" that are executed atomically that means that no context switch can interfere with the operation. In Linux kernel space, we have to atomic_t type, in Java we have the java. util. concurrent.

What is atomic variable in Linux?

There is another solution in linux kernel called atomic variables. Atomic variables are the ones on whom the read modify write operation is done as one instruction with out any interruption .


1 Answers

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

like image 187
Kristina Brooks Avatar answered Sep 30 '22 13:09

Kristina Brooks