UNIX Portable Atomic Operations
For anyone who stumbles upon this in the future, C11 atomics are the best way to do this now - I believe they will be included in GCC 4.9.
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.
As of C11 there is an optional Atomic library which provides atomic operations. This is portable to whatever platform that has a C11 compiler (like gcc-4.9) with this optional feature.
The presence of the atomic can be checked with __STDC_NO_ATOMICS__
and the presence of <stdatomic.h>
atomic.c
#include <stdio.h>
#include <stdlib.h>
#ifndef __STDC_NO_ATOMICS__
#include <stdatomic.h>
#endif
int main(int argc, char**argv) {
_Atomic int a;
atomic_init(&a, 42);
atomic_store(&a, 5);
int b = atomic_load(&a);
printf("b = %i\n", b);
return EXIT_SUCCESS;
}
Compiler invocations
clang -std=c11 atomic.c
gcc -std=c11 atomic.c