Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of atomic structures

Tags:

c

atomic

struct

c11

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?

like image 603
Max Maier Avatar asked Sep 20 '25 11:09

Max Maier


1 Answers

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.

like image 69
Jens Gustedt Avatar answered Sep 23 '25 00:09

Jens Gustedt