初始化malloc'd结构中的原子标志

2tr*_*ill 4 c struct freebsd atomic c11

我正在尝试使用Cclang 3.6.1在FreeBSD 10.1 Release上使用atomics ,但是当我尝试使用ATOMIC_FLAG_INITon get中的atomic_flag变量编译程序时.structerror: 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;
}
Run Code Online (Sandbox Code Playgroud)

我可以在下面的例子中使用like atomic_flag之外structs但不在structs,所以你如何使用原子变量C structs

#include <stdio.h>
#include <stdatomic.h>

int main(void)
{
    atomic_flag flag = ATOMIC_FLAG_INIT;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jen*_*edt 5

atomic_flag 没有可以分配或读取的值,但只有内部状态.

与之交互的唯一方法是为其定义atomic_flag的两个函数(如果计算_explicit版本,则为四个函数).对于你的情况,你的对象通过malloc旗帜处于"不确定状态"(C11的7.17.8 p4).您可以通过应用两个函数之一将其置于已知状态,即用于atomic_flag_clear将其设置为"清除"状态,或者用于atomic_flag_test_and_set将其设置为"设置"状态.

atomic_flag_clear在分配之后使用权限malloc相当于用变量初始化ATOMIC_FLAG_INIT.