Trying out <stdatomic.h>

Поиск
Список
Период
Сортировка
Искать

Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
Вложения:
Hi,

Here is an experimental patch to try out standard C (and C++) atomics
to implement port/atomics.h, and also add more types and operations.
It's mostly just redirecting our names to the standard ones, except
for our barriers and slightly extended pg_atomic_flag, so there isn't
much left of the code.

Here also is a semi-independent patch to implement storage/spin.h with
pg_atomic_flag.  It keeps a small amount of the architecture-specific
magic, but moves it out to src/port/spin_delay.h.

I'm not saying they're correct, performant or portable yet, that'll
require studying codegen and performance on a bunch of weird and
wonderful systems, but they at least passes basic testing on the usual
suspects and CI systems, except for Windows which needs a newer
toolchain so I haven't tried yet.  It should hopefully just work™ on
VS 2022 (same version that provides , about which more
soon).

All that being the case, it's not far enough along to be a serious
proposal, but I imagine others will be looking into things like this
since we pulled the trigger on C11 and I figured I might as well share
a basic working patch set to avoid duplicated effort...   Hopefully it
works well enough to kick the tyres and try to find the difficult
problems, test it out on weird systems, etc etc.

Re: Trying out <stdatomic.h>

От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 10/11/2025 15:17, Thomas Munro wrote:
> Hi,
> 
> Here is an experimental patch to try out standard C (and C++) atomics
> to implement port/atomics.h, and also add more types and operations.
> It's mostly just redirecting our names to the standard ones, except
> for our barriers and slightly extended pg_atomic_flag, so there isn't
> much left of the code.

>  9 files changed, 166 insertions(+), 1824 deletions(-)
>  ...
>  8 files changed, 176 insertions(+), 881 deletions(-)
>  ...
>  7 files changed, 1 insertion(+), 394 deletions(-)

Nice!

> [PATCH v1 1/4] Add some missing #include .

This seems like a good thing regardless of the other patches.

The "#include " lines in src/backend/lib/dshash.c and 
src/backend/storage/lmgr/condition_variable.c are slightly misplaced: 
system headers should be included between "postgres.h" and other 
postgres headers.

> Here also is a semi-independent patch to implement storage/spin.h with
> pg_atomic_flag.  It keeps a small amount of the architecture-specific
> magic, but moves it out to src/port/spin_delay.h.

Makes sense.

The patch removes 'src/template/solaris'. Is that on purpose? Is that an 
independent cleanup that could be committed immediately?

- Heikki



Re: Trying out <stdatomic.h>

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Heikki Linnakangas  writes:
> The patch removes 'src/template/solaris'. Is that on purpose? Is that an 
> independent cleanup that could be committed immediately?

Our four Solaris+illumos buildfarm animals would be sad.

			regards, tom lane


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Tue, Nov 11, 2025 at 4:19 AM Tom Lane  wrote:
> Heikki Linnakangas  writes:
> > The patch removes 'src/template/solaris'. Is that on purpose? Is that an
> > independent cleanup that could be committed immediately?
>
> Our four Solaris+illumos buildfarm animals would be sad.

Looks like I overdid it while rebasing over the commit that removed
the dead Sun compiler... will put that bit back.


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
Вложения:
On Tue, Nov 11, 2025 at 2:57 AM Heikki Linnakangas  wrote:
> > [PATCH v1 1/4] Add some missing #include .
>
> This seems like a good thing regardless of the other patches.

Pushed.

> The patch removes 'src/template/solaris'. Is that on purpose?

Fixed.

It passes with VS 2022 on CI.  I had to skip some assertions about
macros promising lock-free implementation, that it doesn't define in C
mode yet.  They are definitely lock-free though[1], and the macros are
defined for C++, and the same under the covers...  Perhaps
feature/conformance macros won't be defined until a few remaining
pieces (things we don't care about) are accessible from C?  (I see
that Visual Studio 2026 has also just shipped a couple of days ago,
not investigated.)

[1] https://devblogs.microsoft.com/cppblog/c11-atomics-in-visual-studio-2022-version-17-5-preview-2/

Re: Trying out <stdatomic.h>

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 13.11.25 12:35, Thomas Munro wrote:
> It passes with VS 2022 on CI.  I had to skip some assertions about
> macros promising lock-free implementation, that it doesn't define in C
> mode yet.  They are definitely lock-free though[1], and the macros are
> defined for C++, and the same under the covers...  Perhaps
> feature/conformance macros won't be defined until a few remaining
> pieces (things we don't care about) are accessible from C?  (I see
> that Visual Studio 2026 has also just shipped a couple of days ago,
> not investigated.)

Note also that we still have buildfarm members with gcc <4.9, which is 
required for stdatomic.h/_Atomic there.

We could most likely resolve to get rid of them when the time comes, but 
let's not forget to plan that.



Re: Trying out <stdatomic.h>

От:
Aleksander Alekseev <aleksander@tigerdata.com>
Дата:
Hi Thomas,

> It passes with VS 2022 on CI.  I had to skip some assertions about
> macros promising lock-free implementation, that it doesn't define in C
> mode yet.  They are definitely lock-free though[1], and the macros are
> defined for C++, and the same under the covers...  Perhaps
> feature/conformance macros won't be defined until a few remaining
> pieces (things we don't care about) are accessible from C?  (I see
> that Visual Studio 2026 has also just shipped a couple of days ago,
> not investigated.)

Thanks for working on this. I checked v2 on Linux x64 with and without
Valgrind and it passed all the tests. I haven't looked at the code
closely yet.


--
Best regards,
Aleksander Alekseev


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Thu, Nov 20, 2025 at 12:23 AM Peter Eisentraut  wrote:
> On 13.11.25 12:35, Thomas Munro wrote:
> > It passes with VS 2022 on CI.  I had to skip some assertions about
> > macros promising lock-free implementation, that it doesn't define in C
> > mode yet.  They are definitely lock-free though[1], and the macros are
> > defined for C++, and the same under the covers...  Perhaps
> > feature/conformance macros won't be defined until a few remaining
> > pieces (things we don't care about) are accessible from C?  (I see
> > that Visual Studio 2026 has also just shipped a couple of days ago,
> > not investigated.)
>
> Note also that we still have buildfarm members with gcc <4.9, which is
> required for stdatomic.h/_Atomic there.

Those are EOL'd RHEL/Centos 7 and SUSE 12 systems.  A decision to
require GCC 4.9+ might not be fatal to them though, as those distros
had optional newer tool chain packages too.  I'm not sure what
problems could follow from that, probably not much as far as C goes?
C++ ABI questions are always harder but such old systems couldn't
possibly use LLVM as we chop old releases based on distro EOL dates,
and LLVM adopts new language standards (being a compiler project after
all).  (It'll be interesting to see what happens when LLVM requires
C++23, and then RHEL's new rolling LLVM upgrade policy meets its 10
year old stable compiler policy...)

The elephant in the room is Visual Studio.  We have drongo on 2019,
hammerkop on 2022, and CI on 2019 but ready to flip to 2022 whenever
we're ready.  There is no testing for 2026, being only a few days old
(I heard from Bilal that our CI passed when he tried it out FWIW).
2019 fell out of "mainstream" support 1.6 years ago[1], "extended"
support lasts 3.4 more years, and 2017's "extended" support also lasts
1.4 more years, which didn't stop commit 8fd9bb1d from chopping it to
gain some C11 support.  When could we chop 2019 too, to gain more C11
support?

What motivation do people have to use old compilers for new software?
If my google-search-fu is serving me, upgrades are either free
(community edition for individuals, also for organisations working on
open source) or included in various paid subscriptions.  Is there a
technical reason to be more conservative, for example, in terms of
library versions on the target system, something to do with UCRT or
_WIN32_WINNT versions that the EDB installer needs to target before
you can use this stuff?  I can't find anything saying so.  Perhaps
it'd be better to wait until /experimental:c11atomics isn't needed
though.  My impression so far is that that's about conformance with
details we don't care about, not the maturity of the codegen which is
used far and wide in C++, it's just that C conformance is a distant
second priority (1½ decades later), but...  (Not that this project is
finished anyway, more study and validation required.)

[1] https://learn.microsoft.com/en-us/lifecycle/products/visual-studio-2019


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Thu, Nov 20, 2025 at 3:03 AM Aleksander Alekseev
 wrote:
> Thanks for working on this. I checked v2 on Linux x64 with and without
> Valgrind and it passed all the tests. I haven't looked at the code
> closely yet.

Thanks for testing!

The next thing on my TODO list for this is some kind of codegen diff
on a full matrix of targets.


Re: Trying out <stdatomic.h>

От:
"Greg Burd" <greg@burd.me>
Дата:

On Mon, Nov 10, 2025, at 10:19 AM, Tom Lane wrote:
> Heikki Linnakangas  writes:
>> The patch removes 'src/template/solaris'. Is that on purpose? Is that an 
>> independent cleanup that could be committed immediately?
>
> Our four Solaris+illumos buildfarm animals would be sad.
>
> 			regards, tom lane

I have another Illumos animal in the works, but if the plan is to deprecate that platform I can set that aside.  As an old Sun engineer I hate to see it disappear, but it is basically EOL at this point.

-greg


Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:

On Mon, Nov 10, 2025, at 8:17 AM, Thomas Munro wrote:
> Hi,
>
> Here is an experimental patch to try out standard C (and C++) atomics
> to implement port/atomics.h, and also add more types and operations.
> It's mostly just redirecting our names to the standard ones, except
> for our barriers and slightly extended pg_atomic_flag, so there isn't
> much left of the code.
>
> Here also is a semi-independent patch to implement storage/spin.h with
> pg_atomic_flag.  It keeps a small amount of the architecture-specific
> magic, but moves it out to src/port/spin_delay.h.
>
> I'm not saying they're correct, performant or portable yet, that'll
> require studying codegen and performance on a bunch of weird and
> wonderful systems, but they at least passes basic testing on the usual
> suspects and CI systems, except for Windows which needs a newer
> toolchain so I haven't tried yet.  It should hopefully just work™ on
> VS 2022 (same version that provides , about which more
> soon).
>
> All that being the case, it's not far enough along to be a serious
> proposal, but I imagine others will be looking into things like this
> since we pulled the trigger on C11 and I figured I might as well share
> a basic working patch set to avoid duplicated effort...   Hopefully it
> works well enough to kick the tyres and try to find the difficult
> problems, test it out on weird systems, etc etc.
>
> Attachments:
> * v1-0001-Add-some-missing-include-limits.h.patch
> * v1-0002-Redefine-port-atomics.h-on-top-of-stdatomic.h.patch
> * v1-0003-Use-atomics-API-to-implement-spinlocks.patch
> * v1-0004-Remove-configure-meson-checks-for-atomics.patch

Hello Thomas,

First off, thanks for working on this set of changes.  I like your changes in general, except for removing Solaris/Illumos (but I get it).  ;-P

As mentioned on a separate thread about fixing ARM64 support when building with MSVC on Win11 [1] I tried out this patch.  The reply on that thread had an issue with _mm_pause() in spin_delay(), it turns out we need to use __yield() [2].  I went ahead and fixed that, so ignore that patch on the other thread [1].  The new patch attached that layers on top of your work and supports that platform, there was one minor change that was required:


#ifdef _MSC_VER

	/*
	 * If using Visual C++ on Win64, inline assembly is unavailable.  Use a
	 * _mm_pause intrinsic instead of rep nop. For ARM64, use the __yield()
	 * intrinsic which emits the YIELD instruction as a hint to the processor.
	 */
#if defined(_M_ARM64)
	__yield();
#elif defined(_WIN64)
	_mm_pause();
#else
	/* See comment for gcc code. Same code, MASM syntax */
	__asm		rep nop;
#endif
#endif							/* _MSC_VER */


Visual Studio 2026 (Community)
cl (msvc 19.50.35718 "Microsoft (R) C/C++ Optimizing Compiler Version 19.50.35718 for ARM64")
link 14.50.35718.0


tests are passing, best.

-greg

[1] https://www.postgresql.org/message-id/3c576ad7-d2da-4137-b791-5821da7cc370%40app.fastmail.com
[2] https://learn.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics?view=msvc-180

Re: Trying out <stdatomic.h>

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
"Greg Burd"  writes:
> I have another Illumos animal in the works, but if the plan is to deprecate that platform I can set that aside.  As an old Sun engineer I hate to see it disappear, but it is basically EOL at this point.

I think we can keep it going as long as there are people interested
in it.  The gating factor at present is probably whether it can
provide an adequate C11 environment.  But so far I've observed no
issues with the existing BF members.

			regards, tom lane


Re: Trying out <stdatomic.h>

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2025-Nov-23, Tom Lane wrote:

> "Greg Burd"  writes:
> > I have another Illumos animal in the works, but if the plan is to deprecate that platform I can set that aside.  As an old Sun engineer I hate to see it disappear, but it is basically EOL at this point.
> 
> I think we can keep it going as long as there are people interested
> in it.  The gating factor at present is probably whether it can
> provide an adequate C11 environment.  But so far I've observed no
> issues with the existing BF members.

Right -- we have

billbug		Solaris 11.4.81 CBE 04.2025	gcc 14.2.0
hake		OpenIndiana / Illumos		gcc 9.3.0
margay		Solaris 11.4.42 CBE		gcc 11.2.0
pollock		OmniOS / illumos		gcc 10.2.0


Hake actually says:
  gcc (OpenIndiana 13.3.0-oi-2) 13.3.0

and pollock:
  gcc (OmniOS 151054/14.2.0-il-1) 14.2.0

so it looks like the oldest is Margay's 11.2, which claims [1] to
support C11, though there are some bugs that were claimed fixed in later
releases of GCC 11.x related to alignment[2].  Perhaps relevant, but I
only searched the strings "align" and "c11" there, they may not apply to
our usage.  At least the owner of margay and billbug is active, so we
can probably get the compiler in these machines updated if needed.


[1] https://gcc.gnu.org/onlinedocs/gcc-11.2.0/gcc/Standards.html#C-Language
[2] https://gcc.gnu.org/bugzilla/buglist.cgi?bug_status=RESOLVED&resolution=FIXED&target_milestone=11.3
    and further for 11.4, 11.5, 11.6.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Mon, Nov 24, 2025 at 6:02 AM Tom Lane  wrote:
> "Greg Burd"  writes:
> > I have another Illumos animal in the works, but if the plan is to deprecate that platform I can set that aside.  As an old Sun engineer I hate to see it disappear, but it is basically EOL at this point.
>
> I think we can keep it going as long as there are people interested
> in it.  The gating factor at present is probably whether it can
> provide an adequate C11 environment.  But so far I've observed no
> issues with the existing BF members.

Yeah, Solaris has caused comparatively little trouble, if you exclude
the defunct compiler and a build farm animal running a frozen zombie
Solaris version.  It's pretty easy for Linux users to understand
because of its huge influence on standards and conventions back in the
90s.  The buildfarm animals are maintained by people with a real
interest in PostgreSQL on both OSes, and both OSes fix bugs we report
and track POSIX actively.  We've run on SunOS/BSD and descendents for
coming up 40 (POSTGRES) or 30 (PostgreSQL) years, and I'm hoping we'll
even get to complete that Berkeley to-do item about using threads on
SunOS one of these days...  I just goofed when rebasing the v1 patch
and git rm-ed the template file instead of git add-ing it in v1, but I
fixed that in v2.


Re: Trying out <stdatomic.h>

От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Mon, Nov 24, 2025 at 4:23 AM Greg Burd  wrote:
> As mentioned on a separate thread about fixing ARM64 support when building with MSVC on Win11 [1] I tried out this patch.  The reply on that thread had an issue with _mm_pause() in spin_delay(), it turns out we need to use __yield() [2].  I went ahead and fixed that, so ignore that patch on the other thread [1].  The new patch attached that layers on top of your work and supports that platform, there was one minor change that was required:
>
>
> #ifdef _MSC_VER
>
>         /*
>          * If using Visual C++ on Win64, inline assembly is unavailable.  Use a
>          * _mm_pause intrinsic instead of rep nop. For ARM64, use the __yield()
>          * intrinsic which emits the YIELD instruction as a hint to the processor.
>          */
> #if defined(_M_ARM64)
>         __yield();
> #elif defined(_WIN64)
>         _mm_pause();
> #else
>         /* See comment for gcc code. Same code, MASM syntax */
>         __asm           rep nop;
> #endif
> #endif                                                  /* _MSC_VER */

That makes more intuitive sense... but I didn't know that people *do*
sometimes prefer instruction synchronisation barriers for spinlock
delays:

https://stackoverflow.com/questions/70810121/why-does-hintspin-loop-use-isb-on-aarch64

When reading your patch I was pretty confused by that, because it said
it was fixing a barrier problem and apparently doing so in an
unprincipled place.  I guess we really need to research the best delay
mechanism for our needs on this architecture, independently of the
compiler being used, and then write matching GCC and Visual Studio
versions of that?  I think there were some threads about spinlock
performance on Linux + Graviton with graphs and theories...

> tests are passing, best.

Great news!  Thanks.  It sounds like if I could supply the missing
credible evidence of codegen quality on... all the computers, then I
think we'd be down to just: when can we pull the trigger and require
Visual Studio 2022 and do we trust /experimental:c11atomics?

FTR I had earlier shared some version of this patch with Dave when he
was trying to get his Windows/ARM system going, but I think my earlier
version was probably too broken.  Sorry Dave.  At that stage I was
also trying to do it as an option but keeping the existing stuff
around.  Since then we adopted C11, so this is the all-in version.  I
also hadn't understood a key part of the C11 memory model that your
RISC-V animal taught me and that c5d34f4a fixed, and you can see in
this patch set too, and I'm not sure if Visual Studio is like GCC or
Clang in that respect.  It crossed my mind that this might even be
related to the problem you've noticed with barriers being missing, but
I haven't looked into that.  BTW I believe we could actually change
our code NOT to rely on that, ie to follow the C11 memory model better
and declare eg PgAioHandle::status as atomic_uint8 or whatever (other
non-atomic access would be considered dependent and do the right thing
IIUC), but I'm not sure if it's necessary and that research project
can wait.


Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:

On Nov 23 2025, at 4:08 pm, Thomas Munro  wrote:

> On Mon, Nov 24, 2025 at 4:23 AM Greg Burd  wrote:
>> As mentioned on a separate thread about fixing ARM64 support when
>> building with MSVC on Win11 [1] I tried out this patch.  The reply on
>> that thread had an issue with _mm_pause() in spin_delay(), it turns
>> out we need to use __yield() [2].  I went ahead and fixed that, so
>> ignore that patch on the other thread [1].  The new patch attached
>> that layers on top of your work and supports that platform, there was
>> one minor change that was required:
>>  
>>  
>> #ifdef _MSC_VER
>>  
>>         /*
>>          * If using Visual C++ on Win64, inline assembly is
>> unavailable.  Use a
>>          * _mm_pause intrinsic instead of rep nop. For ARM64, use the __yield()
>>          * intrinsic which emits the YIELD instruction as a hint to
>> the processor.
>>          */
>> #if defined(_M_ARM64)
>>         __yield();
>> #elif defined(_WIN64)
>>         _mm_pause();
>> #else
>>         /* See comment for gcc code. Same code, MASM syntax */
>>         __asm           rep nop;
>> #endif
>> #endif                                                  /* _MSC_VER */
>  
> That makes more intuitive sense... but I didn't know that people *do*
> sometimes prefer instruction synchronisation barriers for spinlock
> delays:
>  
> https://stackoverflow.com/questions/70810121/why-does-hintspin-loop-use-isb-on-aarch64
>  
> When reading your patch I was pretty confused by that, because it said
> it was fixing a barrier problem and apparently doing so in an
> unprincipled place.  I guess we really need to research the best delay
> mechanism for our needs on this architecture, independently of the
> compiler being used, and then write matching GCC and Visual Studio
> versions of that?  I think there were some threads about spinlock
> performance on Linux + Graviton with graphs and theories...

Interesting, I think I was rushing to get past that compile issue rather
than optimizing.  This sounds like yet another place where we should
choose based on arch and it seems hint::spin_loop() does.

>> tests are passing, best.
>  
> Great news!  Thanks.  It sounds like if I could supply the missing
> credible evidence of codegen quality on... all the computers, then I
> think we'd be down to just: when can we pull the trigger and require
> Visual Studio 2022 and do we trust /experimental:c11atomics?

I'm in favor of the stdatomic approach.  I can't speak to codegen
quality on *all the platforms* or how *experimental* c11 atomics are
when using MSVC.

> FTR I had earlier shared some version of this patch with Dave when he
> was trying to get his Windows/ARM system going, but I think my earlier
> version was probably too broken.  Sorry Dave.  At that stage I was
> also trying to do it as an option but keeping the existing stuff
> around.  Since then we adopted C11, so this is the all-in version.  I
> also hadn't understood a key part of the C11 memory model that your
> RISC-V animal taught me and that c5d34f4a fixed, and you can see in
> this patch set too, and I'm not sure if Visual Studio is like GCC or
> Clang in that respect.

Thanks for that work on RISC-V, I appreciate that!  Much more digging to
be done to answer those questions for sure.

> It crossed my mind that this might even be
> related to the problem you've noticed with barriers being missing, but
> I haven't looked into that.  BTW I believe we could actually change
> our code NOT to rely on that, ie to follow the C11 memory model better
> and declare eg PgAioHandle::status as atomic_uint8 or whatever (other
> non-atomic access would be considered dependent and do the right thing
> IIUC), but I'm not sure if it's necessary and that research project
> can wait.

Interesting.  Yeah, let's do one thing and then move to the next, but I
do like the idea.

best.

-greg


Re: Trying out <stdatomic.h>

От:
"Greg Burd" <greg@burd.me>
Дата:
Вложения:
Hey Thomas, hackers,

I think that $subject is interesting because it presents an opportunity to reduce the code we maintain and potentially improve performance.  This thread has languished a bit on the list, so I picked it up.  I've tried it out on my local systems (greenfly, unicorn, icarus, macOS, and a Fedora x86_64 laptop I use as my daily driver) using clang, gcc, and MSVC.  It seems to work, I still need to measure performance.

tested:
  - Linux x86_64 (GCC 14.3.0)
  - Linux RISC-V (GCC 13.3.0, Clang 20.1.2)
  - FreeBSD x86_64 (Clang 19.1.7)
  - Windows ARM64 (MSVC 2022)

I realize we're close to the end of the v19 cycle, but one last look couldn't hurt could it?  Attached is "v3" of his patch set.  Is anyone else interested in this? :)

best.

-greg

> best.
>
> -greg

Re: Trying out <stdatomic.h>

От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 21.03.26 19:39, Greg Burd wrote:
> I think that $subject is interesting because it presents an opportunity to reduce the code we maintain and potentially improve performance.  This thread has languished a bit on the list, so I picked it up.  I've tried it out on my local systems (greenfly, unicorn, icarus, macOS, and a Fedora x86_64 laptop I use as my daily driver) using clang, gcc, and MSVC.  It seems to work, I still need to measure performance.
> 
> tested:
>    - Linux x86_64 (GCC 14.3.0)
>    - Linux RISC-V (GCC 13.3.0, Clang 20.1.2)
>    - FreeBSD x86_64 (Clang 19.1.7)
>    - Windows ARM64 (MSVC 2022)
> 
> I realize we're close to the end of the v19 cycle, but one last look couldn't hurt could it?  Attached is "v3" of his patch set.  Is anyone else interested in this? :)

We currently require MSVC 2019, so before this could be accepted, this 
requirement would need to be adjusted (including documentation, 
buildfarm updates, etc.).  Maybe a bit late for that.


Re: Trying out <stdatomic.h>

От:
"Greg Burd" <greg@burd.me>
Дата:

On Mon, Mar 23, 2026, at 7:57 AM, Peter Eisentraut wrote:
> On 21.03.26 19:39, Greg Burd wrote:
>> I think that $subject is interesting because it presents an opportunity to reduce the code we maintain and potentially improve performance.  This thread has languished a bit on the list, so I picked it up.  I've tried it out on my local systems (greenfly, unicorn, icarus, macOS, and a Fedora x86_64 laptop I use as my daily driver) using clang, gcc, and MSVC.  It seems to work, I still need to measure performance.
>> 
>> tested:
>>    - Linux x86_64 (GCC 14.3.0)
>>    - Linux RISC-V (GCC 13.3.0, Clang 20.1.2)
>>    - FreeBSD x86_64 (Clang 19.1.7)
>>    - Windows ARM64 (MSVC 2022)
>> 
>> I realize we're close to the end of the v19 cycle, but one last look couldn't hurt could it?  Attached is "v3" of his patch set.  Is anyone else interested in this? :)
>
> We currently require MSVC 2019, so before this could be accepted, this 
> requirement would need to be adjusted (including documentation, 
> buildfarm updates, etc.).

Fair point, it does seem that's the minimum supported version (2022).

I'm not a Microsoft marketplace or tools expert, so I can't gauge how hard it is to require 2022 or if that'd impact too many users of PG today on that platform who choose to use MSVC over gcc or clang.

I have even less insight into what Azure uses for the host OS (Linux, FreeBSD or Windows) running Postgres for their services, but lets say it's Windows and they have a requirement for MSVC when compiling.  I'd bet they could switch to 2022 without too much trouble.  Are there others out there that deploy/depend/use PG on Windows and have a strong bias for MSVC (vs clang or gcc)?  I have no idea.

> Maybe a bit late for that.

It is late, and this isn't a small set of changes.  I'd be curious to know if, other than the buildfarm animals that are Wnidows with MSVC < 2022, the rest would work with this change or not.  I'd also like to get some objective data on performance.

Would it be wasted effort for me to get this patch into a form that could be committed, tested on the farm, then rolled back if needed (a single patch)?  Is that even a thing we'd consider trying out?

Maybe the effort is worth it and we consider this again at the start of v20 development?

best.

-greg


Re: Trying out <stdatomic.h>

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
"Greg Burd"  writes:
> On Mon, Mar 23, 2026, at 7:57 AM, Peter Eisentraut wrote:
>> We currently require MSVC 2019, so before this could be accepted, this 
>> requirement would need to be adjusted (including documentation, 
>> buildfarm updates, etc.).

> Fair point, it does seem that's the minimum supported version (2022).

I don't really see why we'd need to do that?  I would expect any such
patch to cope gracefully with the lack of , so it could
continue to support older MSVC by falling back to the older code
paths.  For MSVC in particular, we'd not even need to maintain the
older code paths for arches other than x86 and ARM.

But even disregarding Windows, I'd look with great suspicion on a
patch that proposes to rip out all that handwritten code in favor of
requiring .  That'd be putting a great deal of trust in
code that's not under our control and frankly we have no reason to
trust yet, especially not from the standpoint of performance rather
than just minimum functionality.  Note that the thread title is
"Trying out ", not "We're marrying 
sight-unseen, and there will be no divorce".  So I want to see a
patch that treats  as an alternative implementation,
not The Only Way.

As for timing, this is the sort of patch that we usually feel should
go in near the start of a dev cycle, not near the end.  So I counsel
making sure that it's in shape for commit early in v20, but not
expecting that it will get in now, even temporarily.  There are too
many irons in the fire at this phase of the cycle, and too little
room to disambiguate "Greg broke it" from "somebody else broke it".

			regards, tom lane


Re: Trying out <stdatomic.h>

От:
"Greg Burd" <greg@burd.me>
Дата:

On Mon, Mar 23, 2026, at 10:13 AM, Tom Lane wrote:
> "Greg Burd"  writes:
>> On Mon, Mar 23, 2026, at 7:57 AM, Peter Eisentraut wrote:
>>> We currently require MSVC 2019, so before this could be accepted, this 
>>> requirement would need to be adjusted (including documentation, 
>>> buildfarm updates, etc.).
>

Hi Tom, thanks for chiming in. :)

>> Fair point, it does seem that's the minimum supported version (2022).
>
> I don't really see why we'd need to do that?  I would expect any such
> patch to cope gracefully with the lack of , so it could
> continue to support older MSVC by falling back to the older code
> paths.  For MSVC in particular, we'd not even need to maintain the
> older code paths for arches other than x86 and ARM.

Fair, and I agree.

> But even disregarding Windows, I'd look with great suspicion on a
> patch that proposes to rip out all that handwritten code in favor of
> requiring .  That'd be putting a great deal of trust in
> code that's not under our control and frankly we have no reason to
> trust yet, especially not from the standpoint of performance rather
> than just minimum functionality.

Yes, I 100% agree.  That is a valid concern.

> Note that the thread title is
> "Trying out ", not "We're marrying 
> sight-unseen, and there will be no divorce".

This made me laugh, thank you. :)

> So I want to see a
> patch that treats  as an alternative implementation,
> not The Only Way.

Got it.

> As for timing, this is the sort of patch that we usually feel should
> go in near the start of a dev cycle, not near the end.  So I counsel
> making sure that it's in shape for commit early in v20, but not
> expecting that it will get in now, even temporarily.  There are too
> many irons in the fire at this phase of the cycle, and too little
> room to disambiguate "Greg broke it" from "somebody else broke it".

Yep, that's prudent and you're right to point out that the breaking the farm isn't really a good way to test at this stage.

> 			regards, tom lane

best.

-greg


Re: Trying out <stdatomic.h>

От:
"Greg Burd" <greg@burd.me>
Дата:
Вложения:
Hello,

On the earlier thread Tom asked (paraphrasing) what we'd actually be
buying and giving up by reimplementing port/atomics.h on top of C11
, and whether the generated code and performance hold up
across the weird-and-wonderful platforms.  So, I've tried to take
Thomas's WIP patches and put real numbers behind that question. I've
also made stdatomic opt-in at configure time.


Summary up front:

  - It is opt-in and off by default: -Duse_stdatomic=no (the default)
    keeps the traditional atomics, which are untouched.  This is an
    alternative implementation, not a replacement at this time.
  - There is *no* measurable regression on x86-64.
  - Functionally it works and is tested correct on x86-64, aarch64,
    RISC-V, FreeBSD, and Windows-on-ARM (MSVC).
  - Requires a working C11 : MSVC 2022+ (with
    /experimental:c11atomics), GCC 4.9+/Clang 3.1+.  Anything older
    just builds the traditional path.


The series (v4 on 7b87f08e877 cf-7005) is three patches:

  1. The whole implementation -- build-time detection, the C11 code,
     and the wire-up.  This is the only patch proposed for commit, and
     it is opt-in and off by default (-Duse_stdatomic / --with-stdatomic
     = auto|yes|no, default no).
  2. (not for merge) the benchmark harness, included for transparency.
  3. (not for merge, for discussion) removes the traditional
     implementation entirely, to scope that eventual removal and
     ensure that CI that tests this patch set is testing stdatomics
     not exiting atomics.


Per-operation mapping
---------------------
Every hand-written pg_atomic entry point and how it maps to C11.  "trad"
is what the existing arch-*/generic-* code effectively provides; the
mapping column is the atomic_*_explicit order this series emits.

  operation                | trad semantics    | stdatomic map | notes
  -------------------------+-------------------+---------------+------
  read_u32/u64             | plain, no barrier | seq_cst load  | (1)
  write_u32/u64            | plain, no barrier | relaxed store | (1)
  unlocked_write_u32/u64   | plain, no atomic  | relaxed store | (2)
  read_membarrier_u32/u64  | read + full fence | seq_cst load  |
  write_membarrier_u32/u64 | write + full fence| seq_cst store |
  init_u32/u64             | plain store       | atomic_init   | (3)
  -------------------------+-------------------+---------------+------
  exchange_u32/u64         | full barrier      | seq_cst xchg  |
  compare_exchange_u32/u64 | full barrier      | seq_cst CAS   | (4)
  -------------------------+-------------------+---------------+------
  fetch_add_u32/u64        | full barrier      | seq_cst RMW   |
  fetch_sub_u32/u64        | full barrier      | seq_cst RMW   |
  fetch_and_u32/u64        | full barrier      | seq_cst RMW   |
  fetch_or_u32/u64         | full barrier      | seq_cst RMW   |
  add_fetch_u32/u64        | full barrier      | RMW + add     | (5)
  sub_fetch_u32/u64        | full barrier      | RMW - sub     | (5)
  monotonic_advance_u64    | CAS loop          | CAS loop      | (6)
  -------------------------+-------------------+---------------+------
  init_flag                | store 0/unlocked  | atomic_init   | (7)
  test_set_flag            | TAS, acquire      | fetch_and,acq | (7)
  unlocked_test_flag       | plain read        | relaxed load  | (7)
  clear_flag               | store, release    | release store | (7)
  -------------------------+-------------------+---------------+------
  pg_compiler_barrier      | compiler barrier  | signal_fence  | (8)
  pg_read_barrier          | acquire barrier   | signal+acquire| (8)
  pg_write_barrier         | release barrier   | signal+release| (8)
  pg_memory_barrier        | full barrier      | signal+seq_cst| (8)
  pg_spin_delay            | pause/isb/yield   | unchanged     |

  (1) The crux of this mail -- see "read/write ordering" below.  The
      write is relaxed (plain STR, matching the "no barrier" contract);
      the read is seq_cst, which weak-memory correctness required.
  (2) unlocked_write is a plain non-atomic store when exclusive access
      is guaranteed; relaxed matches.
  (3) init is not atomic; only legal before publication.
  (4) strong CAS, seq_cst on both success and failure paths.
  (5) C11 has no add_fetch/sub_fetch; compose from fetch_* + arith.
  (6) unchanged; built on compare_exchange in atomics.h, no impl needed.
  (7) flag is backed by a 32-bit word, not uint8 -- see "flag width".
      Internal polarity is inverted (1=unlocked) but the public
      contract (test_set returns true on acquire) is identical.
  (8) a bare atomic_thread_fence does not by itself constrain the
      compiler's movement of plain (non-atomic) accesses, so each
      barrier is atomic_signal_fence (compiler barrier) *plus* a
      thread fence -- see "barriers".


What the standard atomics do differently, under the covers
----------------------------------------------------------
Mostly this is renaming our names to the standard ones.  The
non-obvious differences that matter:

* Barriers.  A bare atomic_thread_fence() does not by itself constrain
  the compiler from moving plain, non-atomic accesses across it; our
  pg_read/write/memory_barrier() must order those too.  So each barrier
  is a compiler barrier (atomic_signal_fence) *plus*
  atomic_thread_fence(acquire/release/seq_cst).  Miss the compiler
  barrier and the optimizer will happily reorder non-atomic
  loads/stores across it -- I found this the hard way (lost tuples in
  parallel hash join on RISC-V; more below).

* Flag width.  Standard atomic_flag has no relaxed load, so like
  Thomas's patch I build pg_atomic_flag on an integer.  It must be
  32-bit, not 8-bit: RISC-V has no byte-granular AMO, so an 8-bit
  fetch_and is emulated as a read-modify-write of the whole containing
  word, which clobbers adjacent bytes in a packed slock_t.  (generic.h
  already uses uint32 for exactly this reason.)  Note that Heikki's
  in-flight "Replace pg_atomic_flag with pg_atomic_bool" patch removes
  pg_atomic_flag entirely; I'll rebase onto pg_atomic_bool rather than
  reimplement the flag, which also makes the polarity note (7) moot.

* RMW ops (fetch_add, compare_exchange, exchange) are seq_cst in both
  the old and new worlds, so those are unchanged.

* Lock-free, asserted.  PostgreSQL's atomics live in shared memory and
  are touched from multiple processes, not just threads.  A
  non-lock-free _Atomic that the compiler lowers to a libatomic lock
  table would use process-local locks and silently corrupt shared
  state.  So this asserts at compile time, per width, that the atomics
  are genuinely lock-free
  (StaticAssertDecl(ATOMIC_{CHAR,SHORT,INT,LLONG}_LOCK_FREE == 2, ...)),
  as Thomas's patch did; dropping those would be a footgun specific to
  our cross-process usage.  Relatedly, the configure/meson probe is a
  *link* test with a -latomic fallback, not just a compile test: a
  64-bit compare-exchange can lower to a libatomic call
  (__atomic_compare_exchange_8) on some 32-bit targets, where a
  compile-only check would pass and then fail at final link.


read/write ordering: the interesting mistake
---------------------------------------------
This is where I changed my mind, and it's the part worth reviewing.

pg_atomic_read_u32/write_u32 have always been documented as plain
atomic (non-torn) accesses with *no barrier semantics*.  On ARM that
is exactly LDR/STR; on RISC-V a plain lw/sw.  The faithful C11 mapping
of that contract is memory_order_relaxed.  That is right for the write.
It turned out NOT to be safe for the read on weak-memory hardware, and
my first cut got the fix backwards -- I strengthened both when only the
read needed it.

My first cut shipped seq_cst for read/write.  The reason was a real
correctness failure: on RISC-V, a parallel hash join intermittently
lost a tuple (join_hash "extremely_skewed", 19999 instead of 20000
rows), stdatomic build only.  Bisected on the hardware: relaxed fails,
seq_cst passes 10/10.  seq_cst made the symptom go away, so I shipped
it -- as a blanket default on the generic read/write.

That was a blunt over-fix, and the benchmarks are the evidence.  On
aarch64, atomic_store_explicit(seq_cst) compiles to STLR (store-
release); a plain write is STR.  Under cross-core contention on a hot
line (LWLock state on release, buffer header state), STLR drains the
store buffer and joins the total store order, serializing writers.  A
contended-write microbench shows the shape starkly (yes = stdatomic,
threads hammering one line):

  threads   yes ns    no ns    ratio
      2      0.427    0.256    1.67x
      4      0.392    0.130    3.02x
      8      0.482    0.103    4.68x
     16      0.471    0.099    4.76x

Uncontended, single-threaded, they're identical (write_u32 0.511 vs
0.509 ns; read_u32 0.919 vs 0.916 ns) -- LDAR/STLR in isolation cost
nothing here.  The cost is purely the store-ordering under contention.
Read-only pgbench is dense in exactly those hot atomic writes on lock
acquire/release, so the microscopic per-op difference compounded into
the end-to-end ~2% below.  x86 is immune: on TSO a seq_cst load is a
plain mov and a store is cheap, so read/write ordering is nearly free
regardless.  In other words the 2% and the 4.8x are both symptoms of
one wrong decision: strengthening a read/write path whose documented
contract never asked for it.

The right question is whether the write and the read need the same
treatment.  They do not.  I bisected the read on RISC-V (join_hash,
with the compiler+thread-fence barrier fix described above already in
place):

  read variant                          join_hash
  traditional volatile load (stock)      20/20   PASS
  C11 relaxed atomic load                 2/20   (broken)
  C11 relaxed load + compiler barrier     4/20   (broken)
  C11 seq_cst atomic load                15/15   PASS
  (all with write relaxed; acquire read also failed, 2/12.)

The surprise is the top two rows: the traditional volatile load passes
20/20, but a C11 memory_order_relaxed load of the same variable fails
2/20 -- on the same hardware, with identical barriers.  They are not
equivalent.  A volatile access can't be reordered by the compiler
relative to the surrounding pg_read_barrier()/spinlock, so those
barriers actually constrain it; a relaxed atomic the compiler may hoist
or sink across them, defeating the barrier at the consumer.  Wrapping
the relaxed load in a compiler barrier isn't enough either (4/20).
Only seq_cst reproduces what the volatile load gave us.  So the write
goes back to relaxed (plain STR, matching stock's "no barrier"
contract and erasing the contended-store penalty above), and the read
stays seq_cst.

I want to be honest that I first tried the narrower thing, because it's
the obvious objection: return the generic read to relaxed (its
documented "no barrier" contract) and instead order the one parallel
hash-join consumer that lost the tuple -- a pg_read_barrier() in
ExecParallelHashFirstTuple() between reading the bucket head and
dereferencing the tuple it points to.  On RISC-V that did NOT work:
join_hash still lost a tuple, about 1 run in 4, the same as relaxed
with no consumer barrier at all:

  read variant                                   join_hash
  C11 relaxed load + pg_read_barrier() at the
    hash-join bucket-read consumer               fails (~1 in 4)

The lesson is that the ordering the seq_cst read provides is not
localized to that one bucket read.  The parallel hash join reaches
shared state through the Barrier / condition-variable / LWLock
machinery as well, and all of those do pg_atomic_read_u32() and were
quietly relying on the compiler-ordering the traditional *volatile*
load gave for free.  Relaxing the generic read loses that property
everywhere at once; re-establishing it consumer-by-consumer would mean
auditing and barriering many call sites across lmgr/ipc/executor -- a
much larger and riskier change than this port.  So the read stays
seq_cst: it is the single change that restores, tree-wide, exactly the
property the volatile load provided, and -- per the numbers below --
it costs nothing measurable end-to-end.

On the memory-model shape: a seq_cst read paired with a relaxed write
does not by itself establish a single total order over read and write.
The read's seq_cst is there specifically to restore the
compiler-ordering property the old volatile read had, which is what the
consumers depended on -- not to claim a read/write total order.  If
someone sees how to return the generic read to relaxed without a
tree-wide consumer audit, I would genuinely like to know; I could not
find one that survives RISC-V.

Re-benchmark with read=seq_cst + write=relaxed, RO pgbench,
backends pinned to one NUMA node, clients on the other, 8 x 45s runs
per point, A/B alternated, median tps, Mann-Whitney p:

  clients   aarch64 ratio (p)     x86 ratio (p)
      1       1.023 (0.009)        1.013 (0.002)
      4       1.007 (0.021)        1.000 (0.916)
     16       1.013 (0.001)        1.002 (0.074)
     48       1.020 (0.001)        1.007 (0.002)
     96       1.000 (0.529)        1.002 (0.141)

(ratio = stdatomic / stock; >1 means stdatomic faster.)  The ~2%
aarch64 regression is gone -- stdatomic is now at parity-to-slightly-
faster on both arches.  The only sub-1.0 cells are at 192 clients,
where backends are oversubscribed past the one node's core count; that
is placement noise, not an atomics signal.


Test methodology
----------------
Two bare-metal EC2 instances, 192 vCPU / 2 NUMA nodes each: Intel
Sapphire Rapids (m7i.metal-48xl) and Graviton5 (c9g.metal-48xl).  Turbo
off, governor=performance, THP off, numa_balancing off, explicit
hugepages, irqbalance off.  Both variants built from one checkout, same
compiler/flags, only -Duse_stdatomic differing, buildtype=release,
cassert=off.  Dataset cache-resident (scale 100, shared_buffers
32-64GB) so I measure the lock/atomic paths, not I/O; fsync=off,
synchronous_commit=off for the same reason.  pgbench -M prepared, -S
read-only and -N write.  Clients swept 1..256; 10 x 60s measured runs
per (variant, clients, workload), A/B alternated to cancel drift;
median, MAD, ratio with bootstrap 95% CI, and Mann-Whitney U.  Plus a
standalone microbench linked against the installed port/atomics.h that
times each pg_atomic_* op directly, uncontended and contended.

NUMA placement.  For consistent numbers I pinned all backends to NUMA
node 0 and pgbench to node 1.  That deliberately holds the server on a
single node, so sweeping clients past one node's physical core count
measures core oversubscription on node 0, not NUMA-spanning scaling --
the high-client "knee" cells are that oversubscription, not a memory-
locality effect.  I also ran a cross-node placement (backends
interleaved across both nodes with numactl --interleave=all, pgbench
floating) to check for a stdatomic-specific NUMA interaction.  Result:
none.  Interleaving makes both variants slower in absolute terms (more
cross-node cache traffic, as expected), and the stdatomic/stock ratio
under interleave swings both directions across client counts and is
dominated by placement and oversubscription noise, not by any
consistent stdatomic penalty.  That matches the mechanism -- the
seq_cst read cost is a per-core store-order effect, not a cross-socket
coherence effect -- so I don't see a NUMA angle here, which is what I
expected but wanted to confirm rather than assume.


Numbers
-------
x86-64, read-only and write: parity.  Every cell within +/-0.5% of
stock, MAD ~0.1%.  A few cells cross p<0.05 only because the variance
is so small; the effect is in the noise floor and both directions
appear.  As expected on TSO.

aarch64 read-only, first cut (blanket seq_cst read/write) -- consistent
regression, tight CI, p<0.001:

  clients   yes tps      no tps     ratio   95% CI
      1      74,227      75,127     0.988   [0.980, 0.992]
      4     286,689     291,934     0.982   [0.977, 0.985]
     16   1,126,114   1,143,962     0.984   [0.982, 0.987]
    192   3,563,812   3,624,204     0.983   [0.983, 0.984]
    256   3,525,938   3,599,808     0.979   [0.978, 0.981]

i.e. ~1.5-2% slower across the board (c=64/96 invert; that's the
oversubscription knee, high MAD, not signal).  aarch64 write (-N) is
within noise.

aarch64 read-only, the fix (seq_cst read + relaxed write) -- re-bench,
backends on node 0, clients on node 1, 8 x 45s runs/point, ratio =
stdatomic/stock, Mann-Whitney p:

  clients   yes tps       no tps      ratio    p
      1        76,931       75,195    1.023   0.009
      4       291,624      289,523    1.007   0.021
     16     1,142,676    1,128,195    1.013   0.001
     48     3,117,124    3,056,956    1.020   0.001
     96     3,406,632    3,408,343    1.000   0.529

The regression is gone: stdatomic is now parity-to-slightly-faster on
aarch64, because the write is back to a plain STR while the read's
seq_cst LDAR costs nothing measurable here.  (The 192-client cell dips
below 1.0 on both arches, but that's backends oversubscribed past one
node's core count, not an atomics effect.)

Caveats on the data: Intel is complete (RO+RW, 10 runs/cell).
Graviton5 RO is complete; the Graviton5 -N sweep was re-run separately
with per-cell table re-init (autovacuum-off tpcb bloats across runs)
and is parity/noise.  I have the raw CSVs, per-cell stats, and
microbench data and can share them.  The cross-node NUMA study
(interleaved placement) is described above; I can post those numbers
too if useful.

I'll post the rebased series (on PG master) as attachments in a
follow-up if there's interest.  The correctness findings apply to any
 port: pair every thread fence with a compiler barrier;
make pg_atomic_flag 32-bit; and -- the lesson above -- a C11
memory_order_relaxed load is *not* the same as stock's volatile load.

What this series ships is the split the hardware forced: the generic
WRITE is relaxed (plain STR, matching the "no barrier" contract and
erasing the contended-store penalty), and the generic READ is seq_cst,
which is what RISC-V actually required (15/15) and which -- because the
expensive part was the store, now relaxed -- costs nothing measurable
end-to-end.  I tried the narrower "relax the read, order the one
consumer" alternative and it did not hold up on RISC-V (above), so I am
not proposing it; if there's a way to get the generic read back to
relaxed without a tree-wide consumer audit, I'd welcome it.

best,

-greg

Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:

On Monday, September 14th, 2026 at 3:02 PM, Greg Burd  wrote:

> 
> On Mon, Sep 14, 2026, at 2:48 PM, Peter Eisentraut wrote:
> > On 10.09.26 16:10, Greg Burd wrote:
> >> 1. Is an opt-in, default-off second implementation worth carrying at
> >>     all?  Tom's concern was that this not become The Only Way, hence the
> >>     default.  If the answer is no, that's fine and I'll stop pushing.
> >
> > Depends on what the plan in the long term is.  Just having another 
> > variant available at compile time doesn't accomplish much by itself. 
> > Except that we'd now have even more code to maintain.  What are we 
> > asking people to do with it?  Are we asking for testing?  (What kind?) 
> > What do we do when the testing is complete?
> >
> > Personally, I think a possible valuable outcome would be that we don't 
> > have to maintain our own atomics library at all anymore, and just rely 
> > on the compiler.  This would require, most likely, some intermediate 
> > steps and some testing and so on, but it would be good to clarify what 
> > those steps are and whether this is indeed the goal.
> 
> Hey Peter, thanks for the reply.
> 
> I agree, high level end game goal is to move entirely to stdatomic and remove the atomics we've been maintaining.
> 
> I'd imagined we could do that "testing and so on" while we leave them both in tree and then cut over mid-cycle if all looks good. I'm open to other ideas. I'm happy to try to split this up or ease it into the tree, suggestions welcome.
> 
> best.
> 
> -greg

Rebased on dca6a9e320e attached is v7, nothing significant changed.  I've
left the 0003 patch which removes the non-stdatomic path in the set for
cfbot to chew on this round.

-greg

Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello fellow hackers,

v8 attached, rebased on master (a39ce1c3744), fixed mistakes
introduced in v6/7.

best.

-greg

Re: Trying out <stdatomic.h>

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Greg,

I'm not an expert on atomics, but I tried v8-0001 on macOS arm64 with
-Duse_stdatomic=yes. The full meson suite passes. Two things came up.

1. The header has a C++23 branch, and that branch fails to build
when an extension includes it inside extern "C", which is the usual
way:

    extern "C" {
    #include "postgres.h"
    #include "storage/lwlock.h"
    }

clang 17 failed with "templates must have C++ linkage".

2. pg_atomic_test_set_flag_impl uses atomic_fetch_and_explicit(). On
x86 clang turns that into a lock cmpxchg loop, while master uses a
single xchg.

Maybe use atomic_exchange_explicit(ptr, 0, memory_order_acquire) ?

Thanks,
Shihao



Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Tue, 20 Oct 2026 20:56:45 -0400, shihao zhong  wrote:
> Hi Greg,

Hi Shihao,

Thanks very much for testing this on macOS arm64 and for two very
specific reports -- both were real, and both are fixed in v9 attached
(rebased on master df64d6e984b).

> 
> 1. The header has a C++23 branch, and that branch fails to build
> when an extension includes it inside extern "C", which is the usual
> way:
> 
>     extern "C" {
>     #include "postgres.h"
>     #include "storage/lwlock.h"
>     }
> 
> clang 17 failed with "templates must have C++ linkage".

Confirmed and fixed.

> 2. pg_atomic_test_set_flag_impl uses atomic_fetch_and_explicit(). On
> x86 clang turns that into a lock cmpxchg loop, while master uses a
> single xchg.
> 
> Maybe use atomic_exchange_explicit(ptr, 0, memory_order_acquire) ?

Adopted, thank you.   Exchange is the better way to write it regardless.

> Thanks,
> Shihao

best.

-greg

Re: Trying out <stdatomic.h>

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Greg,

I tried v9-0001 on macOS arm64 on current master. I think everything
looks good.

One new thing. It looks like part of 0003 moved into 0001 in this
rebase. In v9-0001, the autoconf and meson builds no longer read the
stdatomic option and always define USE_STDATOMIC_H. 

So 0001 is not opt-in anymore, and a target without lock-free 64-bit
atomics now fails at configure. The commit message still says the
default is "no". 

Thanks,
Shihao

Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Wed, 21 Oct 2026 23:54:40 -0400, shihao zhong  wrote:
> Hi Greg,

Hi Shihao,

> One new thing. It looks like part of 0003 moved into 0001 in this
> rebase. In v9-0001, the autoconf and meson builds no longer read the
> stdatomic option and always define USE_STDATOMIC_H.
>
> So 0001 is not opt-in anymore, and a target without lock-free 64-bit
> atomics now fails at configure. The commit message still says the
> default is "no".

You're right, thanks.

v10 attached (rebased on 2786d605715) puts it back where it belongs:

- 0001 reads the option again in both build systems, default 'no'.  The
   lock-free requirement now lives *inside* the probe, so a target whose
   64-bit atomics are lock-emulated just fails detection and keeps the
   traditional implementation instead of erroring out.  Only
   --with-stdatomic=yes / -Duse_stdatomic=yes errors, and only because
   you asked for it explicitly.
- 0003 does the option removal and the unconditional USE_STDATOMIC_H,
   as it should.
- The configure.ac help text and comment said the default was 'auto'
   while the code said 'no'; now both say 'no'.

best.

-greg

Re: Trying out <stdatomic.h>

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Greg,

I did some fuzz testing using Opus today and did not find anything.

I also did some manual experiments and I think everything is working fine in
mac.

V10 looks good to me.

Thanks,
Shihao

Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:

On Thursday, October 22nd, 2026 at 9:17 PM, shihao zhong  wrote:

> Hi Greg,
> I did some fuzz testing using Opus today and did not find anything.
> 
> I also did some manual experiments and I think everything is working fine in
> mac.
> 
> V10 looks good to me.
> 
> Thanks,
> Shihao

Hi Shihao,

Thank you for the testing, and for the three real bugs you found along
the way.  I've added you as Reviewed-by.

v11 attached, rebased on master (1910daf9831).  The code is unchanged
from v10; this round only corrects the commit messages, which had
drifted from the code (they still mentioned pg_atomic_uint8/16, which
were removed earlier, a test_atomics module that no longer exists, and
a pg_atomic_flag-based spinlock, when slock_t is a pg_atomic_uint32).

As before, 0003 is named .patch_ so cfbot tests 0001 and 0002 only.

best.

-greg

Re: Trying out <stdatomic.h>

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hi,

As a companion to v11, here is v12: the same work as a single patch
that makes  the only atomics implementation, with no
build option.  It is v11's 0001 and 0003 squashed together without the
benchmark harness; the atomics and spinlock code is byte-identical to
v11's opt-in stdatomic path.

I'm posting it because Peter asked where this is meant to end up, and
because a single patch is the easiest thing to evaluate if the answer
is "all the way".  v11 is still the conservative route: an opt-in
alternative, default off, as Tom asked for.  Which of the two to
pursue is a committer's call, and I'd rather offer both than guess.

What v12 removes: arch-arm.h, arch-ppc.h, arch-x86.h, fallback.h,
generic.h, generic-gcc.h, generic-msvc.h and storage/s_lock.h, plus the
s_lock_test program that exercised the old TAS macros (regress.c's
test_spinlock() still covers spinlocks).  The public pg_atomic_* and
SpinLock* APIs are unchanged.

What it requires: a  whose 32- and 64-bit atomics are
always lock-free.  configure and meson now fail with a clear message
otherwise, rather than falling back.  That does not raise the MSVC
baseline: master already requires Visual Studio 2022 (6319d6372c8),
which provides  with /experimental:c11atomics.

Two things a committer should weigh before committing either version:

- pg_atomic_read_u32/u64 use memory_order_seq_cst, which is stronger
  than their documented "no barrier semantics".  With a relaxed read,
  join_hash intermittently loses a tuple on rv64 built with gcc 13.3
  (gcc 15.2 and clang 21 don't, and restoring the old spinlock doesn't
  help).  I haven't found the cause, so the stronger ordering stays
  until someone does.  It costs an LDAR on ARM64, two fences per load on
  rv64 and an hwsync on POWER, across about 200 call sites, and I
  haven't benchmarked that.
- I've tested on x86-64, aarch64 (macOS arm64 in CI), riscv64 and
  Windows ARM64, but not on POWER, s390x or the Solaris/illumos
  animals.  The buildfarm would be the first real test there.

This is the last I'll post on the thread until there's more interest.
Thanks to Thomas for the original patches, and to Shihao for the
reviews.

best.

-greg
FAQ