Re: using C11's _Atomic()
[email protected] (Tony Cook) Mon, 4 May 2026 08:20:58 +1000
| Newsgroups | perl.perl5.porters |
|---|---|
| Message-ID | <[email protected]> |
On Sun, May 03, 2026 at 05:49:40PM +0100, Dave Mitchell wrote:
> Now, perl core isn't on C11 yet, but I've found that on GCC 14.2 at least,
> just chucking in '#include <stdatomic.h>' allows code to be written using
> _Atomic(), and I've confirmed that such code does indeed start acting
> atomically.
gcc 14 defaults to c17 (or rather gnu17)[1], and gcc doesn't seem to
care which standard you specify for C, other compilers may (and
probably fail the probe, which is a good thing.)
Unfortunately C++ didn't add support for stdatomic.h until C++23[2] so
any C++ XS modules that don't specify at least -std=c++23 may break.
And C++ builds with g++ do break:
tony@venus:~/play$ cat iamatomic.c
#include <stdatomic.h>
_Atomic(int) count;
void
run_thread() {
count++;
}
tony@venus:~/play$ g++ -c -xc++ iamatomic.c
iamatomic.c:3:14: error: expected constructor, destructor, or type conversion before ‘count’
3 | _Atomic(int) count;
| ^~~~~
iamatomic.c: In function ‘void run_thread()’:
iamatomic.c:8:5: error: ‘count’ was not declared in this scope
8 | count++;
| ^~~~~
tony@venus:~/play$ g++ -c -xc++ -std=c++20 iamatomic.c
iamatomic.c:3:14: error: expected constructor, destructor, or type conversion before ‘count’
3 | _Atomic(int) count;
| ^~~~~
iamatomic.c: In function ‘void run_thread()’:
iamatomic.c:8:5: error: ‘count’ was not declared in this scope
8 | count++;
| ^~~~~
tony@venus:~/play$ g++ -c -xc++ -std=c++23 iamatomic.c
tony@venus:~/play$
clang++ seems to always allow stdatomic:
tony@venus:~/play$ clang++ -c -xc++ -std=c++20 iamatomic.c
tony@venus:~/play$ clang++ -c -xc++ -std=c++17 iamatomic.c
tony@venus:~/play$ clang++ -c -xc++ -std=c++14 iamatomic.c
tony@venus:~/play$ clang++ -c -xc++ -std=c++11 iamatomic.c
tony@venus:~/play$ clang++ -c -xc++ -std=c++03 iamatomic.c
tony@venus:~/play$ clang++ -c -xc++ -std=c++98 iamatomic.c
tony@venus:~/play$
Since the contents of intrpvar.h are visible to XS code and most older
C++ XS modules aren't going to require or specify C++23 this is likely
to break things.
Tony
[1] https://gcc.gnu.org/onlinedocs/gcc-14.3.0/gcc/Standards.html#C-Language
[2] https://en.cppreference.com/cpp/standard_library#C_standard_library
C.6.2 in C++20 specifically excludes stdatomic.h and 17.14.1 in C++23
includes it.