How to perform atomic operations on Linux that work on x86, arm, GCC and icc?
Projects are using this:
http://packages.debian.org/source/sid/libatomic-ops
If you want simple operations such as CAS, can't you just just use the arch-specific implementations out of the kernel, and do arch checks in user-space with autotools/cmake? As far as licensing goes, although the kernel is GPL, I think it's arguable that the inline assembly for these operations is provided by Intel/AMD, not that the kernel has a license on them. They just happen to be in an easily accessible form in the kernel source.
Recent standards (from 2011) of C & C++ now specify atomic operations:
- C11:
stdatomic.h
- C++11:
std::atomic
Regardless, your platform or compiler may not support these newer headers & features.
Darn. I was going to suggest the GCC primitives, then you said they were off limits. :-)
In that case, I would do an #ifdef
for each architecture/compiler combination you care about and code up the inline asm. And maybe check for __GNUC__
or some similar macro and use the GCC primitives if they are available, because it feels so much more right to use those. :-)
You are going to have a lot of duplication and it might be difficult to verify correctness, but this seems to be the way a lot of projects do this, and I've had good results with it.
Some gotchas that have bit me in the past: when using GCC, don't forget "asm volatile
" and clobbers for "memory"
and "cc"
, etc.