Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between using ATOMIC_FLAG_INIT and std::atomic_flag::clear

Tags:

c++

c++11

atomic

Are the following two code snippets the same:

std::atomic_flag lock = ATOMIC_FLAG_INIT;

and

std::atomic_flag lock;
lock.clear();

It seems like the second can allow for lock to be in an unknown state for a few clicks

Is the first code snippet always going to have a known state?

like image 953
Glenn Teitelbaum Avatar asked Nov 26 '13 05:11

Glenn Teitelbaum


2 Answers

ATOMIC_FLAG_INIT is an implementation defined macro that is guaranteed to work in expressions like the one you've posted. It comes in handy for initializing an atomic_flag that you may have defined at namespace scope, for instance. It also guarantees that the flag will be cleared and that if the flag itself has static storage duration, the initialization will also be static.

The second set of statements is initialization followed by clearing of the flag. Since the state of atomic_flag is unspecified post default construction, it does mean that the flag is in an unspecified state until the clear() has been executed.

like image 166
Praetorian Avatar answered Sep 28 '22 00:09

Praetorian


Yes (per 29.7[atomics.flag] §4):

The macro ATOMIC_FLAG_INIT shall be defined in such a way that it can be used to initialize an object of type atomic_flag to the clear state. For a static-duration object, that initialization shall be static. It is unspecified whether an uninitialized atomic_flag object has an initial state of set or clear.

like image 26
Zeta Avatar answered Sep 27 '22 22:09

Zeta