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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With