Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIX Portable Atomic Operations

Is there a (POSIX-)portable way in C for atomic variable operations similar to a portable threading with pthread?

Atomic operations are operations like "increment and get" that are executed atomically that means that no context switch can interfere with the operation. In Linux kernel space, we have to atomic_t type, in Java we have the java.util.concurrent.atomic package.

On Linux, the atomic.h file provides atomic operations, but the include is platform dependent e.g. #include <asm-x86_64/atomic.h> and it is not available on Mac OS X in a similar way.

like image 611
dmeister Avatar asked Jul 15 '09 07:07

dmeister


People also ask

What are atomic operations in Unix?

Atomic operations are operations like "increment and get" that are executed atomically that means that no context switch can interfere with the operation. In Linux kernel space, we have to atomic_t type, in Java we have the java. util. concurrent.

What is atomic operation in Linux?

The Linux kernel uses a large variety of "atomic" operations — operations that are indivisible as observed from anywhere within the system — to provide safe and efficient behavior in a multi-threaded environment.

What is an atomic operation example?

An example of atomic operation is instruction execution, usually an instruction feed to the execution unit can't be stopped in the middle. Yet, a statement in high level language results in multiple instructions. It is the root cause of non-atomic operations.

What are pthreads in operating system?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.


1 Answers

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 
like image 163
RubenLaguna Avatar answered Sep 21 '22 11:09

RubenLaguna