我试图在C on FreeBSD 10.1版本中使用atomics,使用clang3.6.1,但是当我试图在struct中的atomic_flag变量上编译一个使用ATOMIC_FLAG_INIT的程序时,我得到了error: expected expression。
这是我正在试图编译的程序。
#include <stdio.h>
#include <stdatomic.h>
struct map
{
atomic_flag flag;
};
int main(void)
{
struct map *m = malloc(sizeof(struct map));
m->flag = ATOMIC_FLAG_INIT;
free(m);
return 0;
}我可以像下面的示例那样在structs之外使用structs,但不能在structs中使用,那么如何在C structs中使用原子变量?
#include <stdio.h>
#include <stdatomic.h>
int main(void)
{
atomic_flag flag = ATOMIC_FLAG_INIT;
return 0;
}发布于 2015-07-20 23:23:24
atomic_flag没有您可以分配或读取的值,但只有内部状态。
与atomic_flag交互的唯一方法是为其定义的两个函数(如果算上_explicit版本的话,则是四个)。对于您的情况,当您通过malloc获得对象时,标志处于“不确定状态”(7.17.8 p4 of C11)。您可以简单地通过应用这两个函数之一将其置于已知状态,即使用atomic_flag_clear将其设置为“清除”状态,或使用atomic_flag_test_and_set将其设置为" set“状态。
在使用atomic_flag_clear分配malloc之后立即使用malloc,相当于使用ATOMIC_FLAG_INIT初始化变量。
https://stackoverflow.com/questions/31526556
复制相似问题