Thread-safe atomic operations in gcc Thread-safe atomic operations in gcc multithreading multithreading

Thread-safe atomic operations in gcc


You could check the gcc documentation. For the current gcc version (4.3.2) it would be chapter 5.47 Built-in functions for atomic memory access - for other gcc versions please check your docs. It should be in chapter 5- Extensions to the C Language Family.

Incidentally, the C compiler makes absolutely no guarantee as to simple store operations being atomic. You cannot rely on that assumption. In order for a machine opcode to be executed atomically, it needs the LOCK prefix.


Up to a certain point, atomic operations in C were provided straight from the kernel sources via the atomic.h header.

However, having kernel headers being used directly in user-space code is a very bad practice, so the atomic.h header file was removed some time ago. Instead we ca now make use of the "GCC Atomic Builtins" which are a far better and more reliable approach.

There is a very good explanation provided by Tudor Golubenco on his blog. He even provides a drop-in replacement for the initial atomic.h file, in case you have some code that needs it.

Unfortunately I'm new to stackoverflow, so I can only use one link in my comments, so check Tudor's post and get enlightened.


On x86 and most other architectures, aligned 4-byte reads and writes are always atomic. The optimizer may skip/reorder reads and writes within a single thread, though.

What you want to do is inform the compiler that other threads may have touched this memory location. (A side effect of pthread_mutex_lock is telling the compiler that other threads may have touched any part of memory.) You may see volatile recommended, but this not in the C specification, and GCC doesn't interpret volatile that way.

asm("" : "=m" (variable));frame->variable = variable;

is a GCC-specific mechanism to say that "variable has been written to, reload it".