UNIX 可移植原子操作 [英] UNIX Portable Atomic Operations

查看:32
本文介绍了UNIX 可移植原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 中是否有(POSIX-)可移植方式用于原子变量操作,类似于 pthread 的可移植线程?

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

原子操作是像增量和获取"这样的操作,它们以原子方式执行,这意味着没有上下文切换可以干扰操作.在 Linux 内核空间中,我们必须 atomic_t 类型,在 Java 中我们有 java.util.concurrent.atomic 包.

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.

在 Linux 上,atomic.h 文件提供原子操作,但包含依赖于平台,例如#include 并且它在 Mac OS X 上没有类似的方式.

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.

推荐答案

从 C11 开始,有一个可选的 原子库,提供原子操作.这可以移植到具有此可选功能的 C11 编译器(如 gcc-4.9)的任何平台.

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.

原子的存在可以通过__STDC_NO_ATOMICS__

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
", b);

    return EXIT_SUCCESS;
}

编译器调用

clang -std=c11 atomic.c
gcc -std=c11 atomic.c

这篇关于UNIX 可移植原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆