Re: using C11's _Atomic()

[email protected] (Dave Mitchell) Mon, 1 Jun 2026 11:24:11 +0100
Newsgroups perl.perl5.porters
Message-ID <[email protected]>
On Thu, May 07, 2026 at 01:10:53AM +0200, Leon Timmermans wrote:
> Strictly it's probably UB, but practically any lock-free atomic type should
> compile down to its underlying type as its representation in either case,
> so I'm not overly worried until I've seen proof otherwise.

So, with PR #24439, I've now got atomics (apparently) working where the
system's ability to use atomics is manually specified via

    Configure -Accflags=-DPERL_USE_ATOMIC

The next step is to convert this to a Configure probe. This is an area I'm
very unfamiliar with, so I would like advice as to whether the proposal
below is technically sound, and also advice on how to add it to Configure,
including what naming conventions to use for all the Configure/config
variables and defines.

I envisage a combined test C/C++ file like the following:

    #ifdef __cplusplus
    #  include <atomic>
    #  define PERL_ATOMIC(atype) std::atomic<atype>
    #else
    #  include <stdatomic.h>
     /* 2 indicates guaranteed to be lock-free */
    #  if ATOMIC_INT_LOCK_FREE == 2 && ATOMIC_POINTER_LOCK_FREE == 2
    #    define PERL_ATOMIC(atype) _Atomic(atype)
    #  endif
    #endif

    #ifdef PERL_ATOMIC
    #  define HAS_ATOMIC
    #else 
    #  define PERL_ATOMIC(atype) atype
    #endif

    struct foo {
        PERL_ATOMIC(int)  a;
        int b;
    };

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

    #ifdef HAS_ATOMIC
        return (long)(&((struct foo *)0)->b) & 0xff;
    #else
        return 255;
    #endif
    }

This would be compiled and run *twice*, once using the C compiler, and
once using the C++ compiler (does Configure locate a C++ compiler?)

If in both cases the file compiles, executes ok, doesn't return 255, and
returns the same value in both cases, then atomics are enabled.
The return value being the same means that the C and C++ compilers are
allocating the same number of bytes to the PERL_ATOMIC(int) in the struct,
giving some confidence that the two compilers are compatible with regard
to atomic ints at least.