Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an atomic flag in a malloc'd structure

I'm trying to use atomics in C on FreeBSD 10.1 Release with clang 3.6.1, however when I try to compile a program using ATOMIC_FLAG_INIT on a atomic_flag variable in a struct I get error: expected expression.

Here is the program I am trying to compile.

#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;
}

I can use atomic_flag outside of structs like in the example below but not in structs, so how do you use atomic variables in C structs?

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

int main(void)
{
    atomic_flag flag = ATOMIC_FLAG_INIT;

    return 0;
}
like image 228
2trill2spill Avatar asked Jul 20 '15 21:07

2trill2spill


1 Answers

atomic_flag doesn't have value that you can assign to or read from, but only an internal state.

The only way to interact with atomic_flag are the two functions (or four if you count the _explicit versions) that are defined for it. For your case when you got your object through malloc the flag is in an "indeterminate state" (7.17.8 p4 of C11). You can simply put it into a known state by applying one of the two functions, that is use atomic_flag_clear to set it to the "clear" state, or use atomic_flag_test_and_set to set it to the "set" state.

Using atomic_flag_clear right after an allocation with malloc is equivalent to an initialization of a variable with ATOMIC_FLAG_INIT.

like image 69
Jens Gustedt Avatar answered Oct 20 '22 22:10

Jens Gustedt