Declaring atomic pointers vs. pointers to atomics

大憨熊 提交于 2020-04-07 05:39:08

问题


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));

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?

(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!)


回答1:


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;

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);


来源:https://stackoverflow.com/questions/42082219/declaring-atomic-pointers-vs-pointers-to-atomics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!