UNIX Portable Atomic Operations

前端 未结 7 1356
生来不讨喜
生来不讨喜 2020-12-05 07:01

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 a

相关标签:
7条回答
  • 2020-12-05 07:44

    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
    
    0 讨论(0)
提交回复
热议问题