Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

<stdatomic.h> — atomic operations

The header for atomic operations on data shared between threads; provides flags and macros describing the lock-free property.

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

Syntax

#include <stdatomic.h>
atomic_flag flag = ATOMIC_FLAG_INIT;

<stdatomic.h> provides atomic types and operations. An implementation defining __STDC_NO_ATOMICS__ need not provide it.

Macros correspond to atomic types: ATOMIC_BOOL_LOCK_FREE → bool; ATOMIC_CHAR_LOCK_FREE → char; ATOMIC_CHAR16_T_LOCK_FREE → char16_t; ATOMIC_CHAR32_T_LOCK_FREE → char32_t; ATOMIC_WCHAR_T_LOCK_FREE → wchar_t; ATOMIC_SHORT_LOCK_FREE → short; ATOMIC_INT_LOCK_FREE → int; ATOMIC_LONG_LOCK_FREE → long; ATOMIC_LLONG_LOCK_FREE → long long; ATOMIC_POINTER_LOCK_FREE → pointers. For applicable integer types, they cover signed and unsigned variants.

Macro values, usable in #if: 0 — never lock-free, 1 — sometimes, 2 — always. Atomic does not mean lock-free; atomic_is_lock_free also queries this property.

ATOMIC_FLAG_INIT initializes atomic_flag to clear. Flag operations are lock-free. The example shows previous states returned by atomic_flag_test_and_set and resetting with atomic_flag_clear.

Examples

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

int main(void)
{
    atomic_flag flag = ATOMIC_FLAG_INIT;
    int first = atomic_flag_test_and_set(&flag);
    int second = atomic_flag_test_and_set(&flag);
    atomic_flag_clear(&flag);
    int third = atomic_flag_test_and_set(&flag);

    printf("%d %d %d\n", first, second, third);
    return 0;
}

Result

0 1 0

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