views:

1326

answers:

5

Is there a (POSIX-)portable way in C for atomic variable operations similar to a portable threading with pthread?

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.atomic package.

On Linux, the atomic.h file provides atomic operations, but the include is platform dependent e.g. #include <asm-x86_64/atomic.h> and it is not available on Mac OS X in a similar way.

A: 

AFAIK there are no cross-platform ways to do atomic operations. There may be a library out there but I don't know of. Its not particularly hard to roll your own, though.

Goz
A: 

I don't think there is.

One way of solving it, licenses permitting of course, would be to copy the relevant per-architecture implementations from e.g. the Linux kernel space. I haven't followed the evolution of those primitives closely, but I would guess that they are indeed primitives, i.e. don't depend upon other services or APIs in the kernel.

unwind
+4  A: 

There are some GCC built-ins, described here.

caf
Nice, limited to GCC, but it would be fine for me.
dmeister
A: 

No, POSIX does not specify any portable lock-free/atomic operations. That's why they have pthreads.

You're either going to have to use non-standard ways or stick with ptrheads for portability.

paxdiablo
A: 

Since you asked for OS X:

(and since cross platformity was raised in this thread.)

OS X has functions OSAtomicAdd32() and friends. They are declared in "/usr/include/libkern/OSAtomic.h". See The Threading Programming guide, section "Using Atomic Operations".

And for Windows, there is InterlockedIncrement() and friends (see MSDN).

Together with the gcc builtins __sync_fetch_and_add() and friends (has been linked above), you should have something for every main desktop platform.

Please note that I did not yet use them by myself, but maybe will do so in the next few days.

someGuy