Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ atomic operations for lock-free structures

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

like image 877
bugmenot77 Avatar asked May 30 '09 23:05

bugmenot77


People also ask

What is a lock-free atomic?

Lock-free usually applies to data structures shared between multiple threads, where the synchronisation mechanism is not mutual exclusion; the intention is that all threads should keep making some kind of progress instead of sleeping on a mutex.

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.

Can multithreading be lock-free?

Lock-free techniques allow multiple threads to work together in a non-blocking way, often achieving incredible performance. As the name suggests, locks are not used. If the idea of a multithreaded program without mutexes makes you uncomfortable, you are quite sane. Yet lock-free systems are pervasive.

Is Cas lock-free?

> CAS is "lock free" only in the sense that it doesn't require the processor to stop the world in order to flip the mutex boolean.


2 Answers

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.

like image 62
gbjbaanb Avatar answered Sep 20 '22 16:09

gbjbaanb


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.

like image 29
Alex Martelli Avatar answered Sep 18 '22 16:09

Alex Martelli