Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

_Atomic — atomic types

_Atomic declares an atomic type. It provides indivisible operations, but does not make an entire sequence of actions atomic.

Version: C23; repository compiler flag, production runtime not attested

Syntax

_Atomic(type-name)
_Atomic int counter = 0;

_Atomic(int) is a type specifier; _Atomic int uses a qualifier. Both forms declare an atomic version of int. In _Atomic(T), T cannot be an array, function, atomic, or qualified type.

Initialize the object before concurrent access. atomic_fetch_add from <stdatomic.h> performs an atomic read–modify–write operation and returns the previous value. Separate reads and writes do not form one atomic operation.

Atomicity guarantees neither lock-free execution nor safety of the entire algorithm. The example requires an implementation supporting atomics.

Examples

#include <stdatomic.h>
#include <stdio.h>

int main(void)
{
    _Atomic(int) counter = 0;
    int before = atomic_fetch_add(&counter, 3);
    int after = atomic_load(&counter);
    printf("%d %d\n", before, after);
    return 0;
}

Result

0 3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources