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?
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.
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 typeatomic_flag
to the clear state. For a static-duration object, that initialization shall be static. It is unspecified whether an uninitializedatomic_flag
object has an initial state of set or clear.
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