Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an atomic_flag

I have a struct, let's call it struct foo, to which I'd like to add an atomic_flag variable. So far, I've been callocing the struct given that it mostly needs to be zero initialized. How should I be initializing the atomic_flag member?

struct foo{
    //...
    atomic_flag a_flg;
    //...
};
struct foo *foop = calloc(1,sizeof *foop);
if(!foop) return -1;

//should I be giving up `calloc` (/`malloc`+`memset`) in favor of `malloc`+this?
*foop = (struct foo){ ATOMIC_FLAG_INIT };

Edit:

I have found this related DR#421 by Jens Gustedt that proposes that zero/default-initialization be made to just work for atomic_flags. How can I find out if it's been accepted?

like image 270
PSkocik Avatar asked Apr 02 '19 13:04

PSkocik


1 Answers

The C11 Standard says on 7.17.8p4:

An atomic_flag that is not explicitly initialized with ATOMIC_FLAG_INIT is initially in an indeterminate state.

And there is no indication of what the atomic_flag type is or its contents, so zero'ing does not help here.

You will need to initialize it to a known state either using the macro or the atomic_flag_clear or atomic_flag_clear_explicit functions.

like image 113
Acorn Avatar answered Oct 17 '22 10:10

Acorn