stdatomic.h function on plain int - yields undefined or implementation defined behaviour?

Viewed 280

With GCC something like this compiles and probably works like expected:

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

int main(int argc, char **argv)
{
    (void)argc;

    int x   = 23;
    // XXX
    // instead of:
    // _Atomic int x = 23;

    int exp = atoi(argv[1]);
    int y   = atoi(argv[2]);

    printf("x = %d, exp = %d, y = %d\n", x, exp, y);

    bool b = atomic_compare_exchange_strong(&x, &exp, y);

    printf("x = %d, exp = %d, y = %d => %s\n", x, exp, y, b ? "true" : "false");
    return 0;
}

The C reference says about such atomic functions:

This is a generic function defined for all atomic object types A. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and volatile (e.g. memory-mapped I/O) atomic variables. C is the non-atomic type corresponding to A.

This implies that the atomic functions like atomic_compare_exchange_strong() are not defined for non-atomic types.

Since int is a non-atomic type does the above code yields undefined behavior?

Or does the C standard specifies this as implementation defined behavior?

(where an implementation is able to define int as atomic type, as well - thus basically making it equivalent to _Atomic int)

1 Answers

Not using _Atomic types for atomic functions is definitely undefined behaviour. I am little surprised the compiler doesn't complain, but C is pretty forgiving. Atomic functions provide a very specific guarantee about how they behave when multiple threads are modifying the same memory location at the same time. Your simple example does not actually demonstrate this.

Read the description of atomic types:

Objects of atomic types are the only objects that are free from data races, that is, they may be modified by two threads concurrently or modified by one and read by another.

By not using atomic types you are no longer guaranteed to be able to access the values in an atomic way, thus making the atomic function useless.

Related