According to C11 § 6.5.2.3
Accessing a member of an atomic structure or union object results
in undefined behavior.
This makes sense since you cannot access a whole structure in general. Still why is _Atomic
then also a type qualifier and not only a type specifier?
In other words what is the purpose of a structure which is qualified as _Atomic
? I'm not allowed to either read or write to any element of it.
#include <stdatomic.h>
struct {
int x;
} _Atomic foo;
int main(void) {
foo.x = 42; // write error
return foo.x; // read error
}
Both accesses of foo.x
result in a warning/error in GCC/Clang---which is perfectly fine w.r.t. the C11 standard. Why would I want to qualifier then a structure as _Atomic
?
You can not access individual members, but always the structure as a whole. Accessing parts of something that is meant to be an atomic unit, makes not much sense, I think.
A typical use case for an atomic structure is the combination of two pointers, e.g. the head and tail of a list. To manipulate such a struct
you would have to copy the current value from the atomic to a temporary, modify that, and then copy back. By that you'd always have a guarantee that the stored value is consistent at any time.
Per default all such operations on a whole atomic struct
have sequential consistency.
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