12

I'm implementing a lock-free mechanism using atomic (double) compare and swap instructions e.g. cmpxchg16b

I'm currently writing this in assembly and then linking it in. However, I wondered if there was a way of getting the compiler to do this for me automatically? e.g. surround code block with 'atomically' and have it go figure it out how to implement the code as an atomic instruction in the underlying processor architecture (or generate an error at compile time if the underlying arch does not support it)?

P.S. I know that gcc has some built-ins (at least for CAS)

http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html#Atomic-Builtins

bugmenot77
  • 621
  • 3
  • 6
  • 14

2 Answers2

12

Already kindof answered here.

The C++0x standard will provide some atomic datatypes, mainly integer and void types using std::atomic<> template. That article mentions Boehm's atomic_ops project which you can download and use today.

If not, can't you implement your assembler inline in the compiler? I know MSVC has the __asm keyword for inline assembler routines. Google says yes, gcc can do it too.

Community
  • 1
  • 1
gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
  • 8
    MSVC has interlocked ops, and GCC has built-in atomic ops functions, so there's no need to do inline assembler. By using the compiler wrappers, you'll stay portable to all platforms supported by the compiler – bdonlan May 31 '09 at 02:01
  • MSVC has interlocked ops for long datatypes only, the OP wanted doubles. – gbjbaanb Jun 01 '09 at 10:50
  • gcc has no built in ops for DWCAS. MSVC has a built in for DWCAS. No OS has DW (double word, e.g. two pointer lengths, side by side) for increment, decrement, etc - DW only exists and only exists (and only has ever existed) for CAS. –  Aug 16 '09 at 09:51
6

The future "C++0x" standard for C++ will support atomic operations &c -- see e.g. http://www.open-std.org/JTC1/sc22/wg21/docs/papers/2007/n2427.html for a reasonably thorought discussion. Until said forthcoming standard is approved and widely implemented, of course, there's no way to get such functionality "portably" across compilers; if you're interested in specific compilers beyond gcc, maybe you can open another question specifically about them.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395