声明原子指针与原子指针 [英] Declaring atomic pointers vs. pointers to atomics

查看:141
本文介绍了声明原子指针与原子指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解以下声明创建了一个值数组,每个值都是原子的:

I understand that the following declaration creates an array of values, each of which is atomic:

_Atomic int x[10];

但是,我不清楚是否这样:

However, I'm unclear on whether this:

_Atomic int *x;
x = calloc(10, sizeof(int));

创建一个由10个原子整数组成的数组,或者是指向非原子整数数组的原子指针.该语法是否声明原子数组或指向该数组的原子指针,无论是哪个,如何声明另一个?

Creates an array of 10 atomic integers, or is an atomic pointer to an array of nonatomic integers. Does that syntax declare an array of atomics or an atomic pointer to an array, and whichever it is, how does one declare the other?

(注意:我知道atomic_int,在给出的示例中,它将消除歧义.这是我实际尝试做的一个简单版本,它使用原子枚举.谢谢!)

(Note: I'm aware of atomic_int, and in the presented example it would remove the ambiguity. This is a simpler version of what I'm actually trying to do, which uses an atomic enum. Thanks!)

推荐答案

它是指向原子整数的指针,请参见

It's pointer to atomic integer, see http://en.cppreference.com/w/c/language/atomic .

要声明指向整数的原子指针,您需要将关键字放在变量之前:

To declare atomic pointer to an integer, you would need to put the keyword right before the variable:

 int * _Atomic x;

请注意,带有calloc的示例可能在通用平台上运行,但通常不能保证非原子变量和原子变量的类型相同.因此,必须使用 atomic_init :

Note that the example with calloc may work on common platforms but generally there is no warranty that the types of non-atomic and atomic variables are the same. So it's necessary to initialize the variables with atomic_init:

 x = calloc(10, sizeof(_Atomic int));
 for (...) atomic_init(&x[i], 0);

这篇关于声明原子指针与原子指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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