pg_threads.h take II
pg_threads.h take II
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
Вложения:
Hi, Here's another go at port/pg_threads.h, a C11 -like interface, with some patches to use it (some just sketch-quality). Previous work: https://www.postgresql.org/message-id/flat/CA%2BhUKGLtmexrpMtxBRLCVePqV_dtWG-ZsEbyPrYc%2BNBB2TkNsw%40mail.gmail.com We still can't require C11 yet, though the interface has a clear future upgrade/remap path to do that eventually. Since I last wrote about this topic, we gained the ability to count on C11 thread_local being available (it's a language/compiler feature and doesn't need a header or library), and partly because of that, but also because I don't think anyone really likes it, I ripped out that tss_t stuff. I came up with a narrower API to get thread-exit cleanup callbacks if you need them for your thread_local resources, same pthread_key_t/FlsAlloc stuff underneath it but without having to get lost in the weeds of conformance. v1-0001-ecpg-Fix-auto_mem-cleanup-on-thread-exit.patch Already discussed in another thread, a couple of existing ECPG thread-exit cleanup bugs need to be fixed (bugs that cancel each other out in master, but leak, and with my patches the leak was fixed in passing but then a double-free would crash): https://www.postgresql.org/message-id/flat/CA%2BhUKGLv202ndx%3DkP1fZJapNcbfnpq-rezHNyt%2BcQ4pdxr1akg%40mail.gmail.com v1-0002-port-Provide-minimal-pg_threads.h-API.patch The main thing I'm wondering about is how to make the error reporting a bit nicer. Neither pthreads nor C11 threads set errno, but it's nice if you can use %m. Hmm. v1-0003-port-Use-pg_threads.h-API-for-pg_localconv_r.patch Trivial. v1-0004-ecpg-Improve-variable-name.patch v1-0005-ecpg-Use-pg_threads.h.patch These demonstrate the replacement of pthread_key_t with thread_local, and where needed, pg_thrd_atexit_t. That's the narrower thing I came up with to replace pthread_t/tss_t with something that more directly models what we want, I think. I could do pg_tss_t, but it takes a lot of extra book-keeping code to make Windows FlsAlloc match the spec. v1-0006-pgbench-Use-pg_threads.h.patch Kills another local thread-porting abstraction. v1-0007-libpq-Use-pg_threads.h.patch Kills another local thread-porting abstraction. v1-0008-pg_basebackup-Use-pg_threads.h.patch Kills the fork() mode used for Unix, harmonises Unix and Windows. v1-0009-pg_dump-Remove-TerminateThread-call.patch This one already has a discussion thread (I figured it might be another back-patchable issue, IDK), and it looks like the solution I used here isn't what we want to go with for the future, but to do it the way Heikki and Jelte are suggesting will probably require deciding how to access atomics or at least compiler barrires in front-end code, which I'll look into this week. Consider this approach a stand-in for now, as I needed to get rid of a TerminateThread() call somehow. We can't have that in pg_threads.h for various reasons (it's all kinds of undefined). https://www.postgresql.org/message-id/flat/CA%2BhUKGJgO%3Do-vLFahGdR2WesuX3h1-0j%3Da8z72fChc-MG1Hveg%40mail.gmail.com v1-0010-pg_dump-Block-signals-during-signal-handler.patch Not very interesting, I was just triggered by steampunk Unix anachronisms in passing... an experimental patch further down replaces all of this anyway. v1-0011-pg_dump-Use-pg_threads.h-and-remove-fork-path.patch Kills the fork() mode used for Unix, harmonises Unix and Windows. After this patch, the cancellation stuff admittedly looks pretty shaky, but I wanted to separate the fork()-ectomy from any larger refactoring, so bear with me... Next I was planning to rip out the pipes that fork()-mode needed and use an in-memory work queue, and probably make a reusable pg_thrd_pool instead of open coding it here, but it turned out that Bryan was already way ahead of me there: https://www.postgresql.org/message-id/flat/8c712d76-ecf7-4749-a6d8-dddc01f298ec@gmail.com Luckily it looks like he started working at that end of the problem and I started with this fork()-ectomy/harmonisation piece, so I think/hope that we can fit those efforts together quite easily... I will look at his patches this week. v1-0012-pg_signal_processor-Infrastructure-for-cleanup.patch v1-0013-fe_utils-Provide-cancel_set-for-fast-quit-paths.patch v1-0014-pg_dump-Refactor-connection-cancel-management.patch I considered lots of different ways to make pg_dump cleanup better, and this is the approach that *seemed* to be roughly along the lines that Jelte suggested he wanted for various reasons, over in the TerminateThread() thread. Namely, make it so that Unix and Windows both run your cleanup code on a thread, but also force Windows to serialise the handlers, so that the semantics match and we can escape from the constraints of async-signal-safe signal handlers. On Unix it has a thread sitting there waiting for you to hit ^C, just looping over sigwait() and calling handlers serially, that are then free to use arbitrarily complex code before _exit() turns out the lights. Warning/disclaimer: 0012-0014 are only experimental sketches trying stuff out, and might not work that well in various ways, I just wanted to get your take on this general direction. Could skin this in lots of other ways too and since you guys are actively hacking on this area you might already have another idea in mind or even patches? After these patches, there are a few places left that use raw Windows threading APIs, but they're places that are creating threads to solve signaling and I/O problems that have better solutions, topics for another email (but briefly I mean: the interrupts/latches refactoring patch can kill "our" signal-emulation threads, and support for overlapped I/O can allow multiplexing pipe I/O with latches without intermediate data-pumping threads (cf Run::IPC which also has that kind of Windows-hates-select() problem), and support for process-exit WaitEvents can kill another helper thread, ... yada yada).
Re: pg_threads.h take II
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Tue, Jul 7, 2026 at 12:09 AM Thomas Munro wrote: > used here isn't what we want to go with for the future, but to do it > the way Heikki and Jelte are suggesting will probably require deciding > how to access atomics or at least compiler barrires in front-end code, > which I'll look into this week. Correction: at least memory barriers
Re: pg_threads.h take II
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 06/07/2026 15:09, Thomas Munro wrote:
> Hi,
>
> Here's another go at port/pg_threads.h, a C11 -like
> interface, with some patches to use it (some just sketch-quality).
> Previous work:
>
> https://www.postgresql.org/message-id/flat/CA%2BhUKGLtmexrpMtxBRLCVePqV_dtWG-ZsEbyPrYc%2BNBB2TkNsw%40mail.gmail.com
>
> We still can't require C11 yet, though the interface has a
> clear future upgrade/remap path to do that eventually. Since I last
> wrote about this topic, we gained the ability to count on C11
> thread_local being available (it's a language/compiler feature and
> doesn't need a header or library), and partly because of
> that, but also because I don't think anyone really likes it, I ripped
> out that tss_t stuff. I came up with a narrower API to get
> thread-exit cleanup callbacks if you need them for your thread_local
> resources, same pthread_key_t/FlsAlloc stuff underneath it but without
> having to get lost in the weeds of conformance.
Nice!
I've now reviewed patches 0001-0007. I think they're ready to be
committed, with some small comments below:
> v1-0002-port-Provide-minimal-pg_threads.h-API.patch
>
> The main thing I'm wondering about is how to make the error reporting
> a bit nicer. Neither pthreads nor C11 threads set errno, but it's
> nice if you can use %m. Hmm.
Perhaps provide a function like:
void
set_errno_from_pg_thrd_error(int error)
{
switch((pg_thrd_error_t) error)
{
case pg_thrd_nomem:
errno = ENOMEM;
break;
case pg_thrd_busy:
errno = EBUSY;
break;
...
}
}
> +/* Convert native error to pg_thrd_error_t. */
> +static inline int
> +pg_thrd_maperror(int error)
> +{
> +#ifdef WIN32
> + return error ? pg_thrd_success : pg_thrd_error;
> +#else
> + return error == 0 ? pg_thrd_success : pg_thrd_error;
> +#endif
> +}
The WIN32 version of this is confusing. There is only one caller of this
with WIN32:
> +#elif defined(WIN32)
> + return pg_thrd_maperror(InitializeSynchronizationBarrier(barrier, count, 0));
> +#else
So that's not wrong. But I'd suggest only defining pg_thrd_maperror()
with pthreads, and handling that one WIN32 caller directly without the
helper function. Maybe rename pg_thrd_maperror() to something like
map_pthread_retval_to_pg_thrd_error() or something.
Do the pthread functions return an errno on error? Currently, all errors
get squashed to pg_thrd_error, which is a little unfortunate.
> +/* Like C11 mtx_type_t. */
> +typedef enum pg_mtx_type_t
> +{
> + pg_mtx_plain = 0
> +} pg_mtx_type_t;
> +
> +/* Like C11 mtx_init(). */
> +static inline int
> +pg_mtx_init(pg_mtx_t *mutex, int type)
> +{
> +#ifdef WIN32
> + return pg_rwlock_init(mutex);
> +#else
> + return pg_thrd_maperror(pthread_mutex_init(mutex, NULL));
> +#endif
> +}
Since we only support plain mutexes, how about "Assert(type ==
pg_mtx_plan)" here?
> +/*-------------------------------------------------------------------------
> + *
> + * Barriers. Not in C11.
> + *
> + *-------------------------------------------------------------------------
> + */
I wonder if we really need barriers. They're not that useful IMHO. I'd
tend to just open-code this directly with a mutex and the condition
variable in most cases. (Not a strong objection, there's little harm in
having it either)
> +/*
> + * Wait for all expected threads to arrive at the barrier, and elect one
> + * arbitrary thread to perform a phase of computation serially. Sets
> + * *elected_thread to true in the elected thread, and false in all others.
> + */
> +static inline int
> +pg_barrier_wait_and_elect(pg_barrier_t *barrier, bool *elected_thread)
> +{
No callers use the *elected_thread return value. What was the idea here?
> +#ifdef WIN32
> +
> + /*
> + * Retrieve handle passed here by pg_thrd_create() before allowing this
> + * thread to run. (pg_thrd_current() can't use CurrentThread(), because
> + * that returns a pseudo-handle with the same value in all threads.)
> + */
> + Assert(start_info->self);
> + my_thrd_handle = start_info->self;
> +#endif
Does that refer to the GetCurrentThreadId() function? We use that in a
few places currently.
How can it return the same value in all threads, isn't that completely
useless? And does that mean all our current uses of it are broken?
- Heikki
Re: pg_threads.h take II
От:
dbryan.green@gmail.com
Дата:
On 7/6/26 3:48 PM, Heikki Linnakangas wrote:
> On 06/07/2026 15:09, Thomas Munro wrote:
> > Hi,
> >
> > Here's another go at port/pg_threads.h, a C11 -like
> > interface, with some patches to use it (some just sketch-quality).
> > Previous work:
> >
> > https://www.postgresql.org/message-id/flat/
> > CA%2BhUKGLtmexrpMtxBRLCVePqV_dtWG-ZsEbyPrYc%2BNBB2TkNsw%40mail.gmail.com
> >
> > We still can't require C11 yet, though the interface has a
> > clear future upgrade/remap path to do that eventually. Since I last
> > wrote about this topic, we gained the ability to count on C11
> > thread_local being available (it's a language/compiler feature and
> > doesn't need a header or library), and partly because of
> > that, but also because I don't think anyone really likes it, I ripped
> > out that tss_t stuff. I came up with a narrower API to get
> > thread-exit cleanup callbacks if you need them for your thread_local
> > resources, same pthread_key_t/FlsAlloc stuff underneath it but without
> > having to get lost in the weeds of conformance.
>
> Nice!
>
> I've now reviewed patches 0001-0007. I think they're ready to be
> committed, with some small comments below:
>
> > v1-0002-port-Provide-minimal-pg_threads.h-API.patch
> >
> > The main thing I'm wondering about is how to make the error reporting
> > a bit nicer. Neither pthreads nor C11 threads set errno, but it's
> > nice if you can use %m. Hmm.
>
> Perhaps provide a function like:
>
> void
> set_errno_from_pg_thrd_error(int error)
> {
> switch((pg_thrd_error_t) error)
> {
> case pg_thrd_nomem:
> errno = ENOMEM;
> break;
> case pg_thrd_busy:
> errno = EBUSY;
> break;
> ...
> }
> }
>
> > +/* Convert native error to pg_thrd_error_t. */
> > +static inline int
> > +pg_thrd_maperror(int error)
> > +{
> > +#ifdef WIN32
> > + return error ? pg_thrd_success : pg_thrd_error;
> > +#else
> > + return error == 0 ? pg_thrd_success : pg_thrd_error;
> > +#endif
> > +}
>
> The WIN32 version of this is confusing. There is only one caller of this
> with WIN32:
>
> > +#elif defined(WIN32)
> > + return pg_thrd_maperror(InitializeSynchronizationBarrier(barrier,
> > count, 0));
> > +#else
>
> So that's not wrong. But I'd suggest only defining pg_thrd_maperror()
> with pthreads, and handling that one WIN32 caller directly without the
> helper function. Maybe rename pg_thrd_maperror() to something like
> map_pthread_retval_to_pg_thrd_error() or something.
>
> Do the pthread functions return an errno on error? Currently, all errors
> get squashed to pg_thrd_error, which is a little unfortunate.
>
> > +/* Like C11 mtx_type_t. */
> > +typedef enum pg_mtx_type_t
> > +{
> > + pg_mtx_plain = 0
> > +} pg_mtx_type_t;
> > +
> > +/* Like C11 mtx_init(). */
> > +static inline int
> > +pg_mtx_init(pg_mtx_t *mutex, int type)
> > +{
> > +#ifdef WIN32
> > + return pg_rwlock_init(mutex);
> > +#else
> > + return pg_thrd_maperror(pthread_mutex_init(mutex, NULL));
> > +#endif
> > +}
>
> Since we only support plain mutexes, how about "Assert(type ==
> pg_mtx_plan)" here?
>
>
> > +/
> > *-------------------------------------------------------------------------
> > + *
> > + * Barriers. Not in C11.
> > + *
> > +
> > *-------------------------------------------------------------------------
> > + */
>
> I wonder if we really need barriers. They're not that useful IMHO. I'd
> tend to just open-code this directly with a mutex and the condition
> variable in most cases. (Not a strong objection, there's little harm in
> having it either)
>
> > +/*
> > + * Wait for all expected threads to arrive at the barrier, and elect one
> > + * arbitrary thread to perform a phase of computation serially. Sets
> > + * *elected_thread to true in the elected thread, and false in all
> > others.
> > + */
> > +static inline int
> > +pg_barrier_wait_and_elect(pg_barrier_t *barrier, bool *elected_thread)
> > +{
>
> No callers use the *elected_thread return value. What was the idea here?
>
> > +#ifdef WIN32
> > +
> > + /*
> > + * Retrieve handle passed here by pg_thrd_create() before
> > allowing this
> > + * thread to run. (pg_thrd_current() can't use CurrentThread(),
> > because
> > + * that returns a pseudo-handle with the same value in all threads.)
> > + */
> > + Assert(start_info->self);
> > + my_thrd_handle = start_info->self;
> > +#endif
>
> Does that refer to the GetCurrentThreadId() function? We use that in a
> few places currently.
>
> How can it return the same value in all threads, isn't that completely
> useless? And does that mean all our current uses of it are broken?
>
> - Heikki
>
>
GetCurrentThread() not GetCurrentThreadId()... GetCurrentThread()
returns a special sentinel handle (-2) that when passed to another
Win32 function causes the kernel to resolve to whatever thread made
the call....
So, no-- not broken.
Re: pg_threads.h take II
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 07/07/2026 00:01, dbryan.green@gmail.com wrote: > On 7/6/26 3:48 PM, Heikki Linnakangas wrote: >> On 06/07/2026 15:09, Thomas Munro wrote: >>> +#ifdef WIN32 >>> + >>> + /* >>> + * Retrieve handle passed here by pg_thrd_create() before >>> allowing this >>> + * thread to run. (pg_thrd_current() can't use CurrentThread(), >>> because >>> + * that returns a pseudo-handle with the same value in all threads.) >>> + */ >>> + Assert(start_info->self); >>> + my_thrd_handle = start_info->self; >>> +#endif >> >> Does that refer to the GetCurrentThreadId() function? We use that in a >> few places currently. >> >> How can it return the same value in all threads, isn't that completely >> useless? And does that mean all our current uses of it are broken? > > GetCurrentThread() not GetCurrentThreadId()... GetCurrentThread() > returns a special sentinel handle (-2) that when passed to another > Win32 function causes the kernel to resolve to whatever thread made > the call.... > > So, no-- not broken. Ah gotcha. Could we use GetCurrentThreadId() here then? (I have no problem with the way it's currently done in the patch either though, just curious) - Heikki
Re: pg_threads.h take II
От:
Bryan Green <dbryan.green@gmail.com>
Дата:
On 7/6/2026 4:13 PM, Heikki Linnakangas wrote: > On 07/07/2026 00:01, dbryan.green@gmail.com wrote: >> On 7/6/26 3:48 PM, Heikki Linnakangas wrote: >>> On 06/07/2026 15:09, Thomas Munro wrote: >>>> +#ifdef WIN32 >>>> + >>>> + /* >>>> + * Retrieve handle passed here by pg_thrd_create() before >>>> allowing this >>>> + * thread to run. (pg_thrd_current() can't use CurrentThread(), >>>> because >>>> + * that returns a pseudo-handle with the same value in all >>>> threads.) >>>> + */ >>>> + Assert(start_info->self); >>>> + my_thrd_handle = start_info->self; >>>> +#endif >>> >>> Does that refer to the GetCurrentThreadId() function? We use that in a >>> few places currently. >>> >>> How can it return the same value in all threads, isn't that completely >>> useless? And does that mean all our current uses of it are broken? >> >> GetCurrentThread() not GetCurrentThreadId()... GetCurrentThread() >> returns a special sentinel handle (-2) that when passed to another >> Win32 function causes the kernel to resolve to whatever thread made >> the call.... >> >> So, no-- not broken. > > Ah gotcha. Could we use GetCurrentThreadId() here then? (I have no > problem with the way it's currently done in the patch either though, > just curious) > > - Heikki > I haven't looked at all of the code, but I would assume there is a WaitFor...Object() somewhere and those only work with actual handles...not id's. GetCurrentThreadId() returns a dword for id. I'll look over the patches as well. -- Bryan Green EDB: https://www.enterprisedb.com
Re: pg_threads.h take II
От:
Peter Eisentraut <peter@eisentraut.org>
Дата:
On 31.07.26 04:18, Thomas Munro wrote: > I decided to split the API patch into two parts, to highlight > something interesting: > > v3-0002 pg_threads.h with support for or > v3-0003 adds option for native Windows API > > If we are ready to make a hard requirement for Visual > Studio builds, and willing to use the implementation that > ships with MinGW, then we don't actually need v3-0003. That means > that we're left with almost no code, mostly just renaming wrappers and > comments. > > CI passes with or without v3-0003. > > I also fixed the commit message for v3-0006 which I'd failed to update > (I abandoned my thread-exit invention and just went with tss_t in the > end). No other changes from v2. What is the status of this patch set? I note that some of the patches had already been reviewed earlier in the thread as good for commit, but I don't think that was done. Have the newer patch set versions invalidated these reviews? I'm looking at some other patch sets that are fiddling with threads and the API layers, and I'm wondering if it's worth proceeding with those, or rather focus on getting this patch set done and then rebase those other ones on top of this new API.
Re: pg_threads.h take II
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Thu, Nov 5, 2026 at 12:19 AM Peter Eisentraut wrote:
> On 31.07.26 04:18, Thomas Munro wrote:
> > I decided to split the API patch into two parts, to highlight
> > something interesting:
> >
> > v3-0002 pg_threads.h with support for or
> > v3-0003 adds option for native Windows API
> >
> > If we are ready to make a hard requirement for Visual
> > Studio builds, and willing to use the implementation that
> > ships with MinGW, then we don't actually need v3-0003. That means
> > that we're left with almost no code, mostly just renaming wrappers and
> > comments.
> >
> > CI passes with or without v3-0003.
> >
> > I also fixed the commit message for v3-0006 which I'd failed to update
> > (I abandoned my thread-exit invention and just went with tss_t in the
> > end). No other changes from v2.
>
> What is the status of this patch set?
>
> I note that some of the patches had already been reviewed earlier in the
> thread as good for commit, but I don't think that was done. Have the
> newer patch set versions invalidated these reviews?
Later versions are similar to what was reviewed, but much more
polished and fleshed out:
* covered the full C11 API
* ditched my made-up at-exit thing (early on I had misdiagnosed why
early attempts to implement pg_tss_t on Win32 APIs crashed and
burned... it turned out I was just confused by pre-existing bugs in
ECPG, see patch 0001)
* split the per-system implementations into _impl.h headers, using
some macros to reduce boiler-plate duplication and mistakes
* added a third implementation that just points to a system
implementation, which we might want to consider
"conformance demonstrating" developer-only build option, or we might
want to decide now or later to use for Windows/MSVC
* split the interface into pg_threads.h and pg_threads_ext.h to
clearly separate the additions to that I think we need
* did more work on determining and documenting exactly why and when
it's safe for pg_threads_ext.h to define static initialisers for each
of the three implementations
* provided a way to get at underlying implementation errors based on
Heikki's comments, see pg_thrd_error_string_with_detail()
* researched the ID vs handle schism that Bryan highlighted on
Windows, and what user-visible impedance mismatch results, what VS's
own does about that, what we should do about it, see
PG_THRDS_CURRENT_NOT_{JOINABLE,DETACHABLE} and
PG_THRD_CURRENT_CONFORMING (ie I showed how to work around it, at a
small cost to pg_thrd_create(), but also that VS's doesn't
bother to do that and instead just fails to conform to C11)
* researched the MinGW situation and realised that although it doesn't
offer yet, its works just fine (relevant
because its lack of would otherwise have cut off the
option of requiring on Windows)
Does anyone want to opine on whether we want v3-0003 or not? If we
don't commit v3-0003, we have onto two implementations and we get:
* Unixen, Windows/MinGW = pthread.h
* Windows/MSVS = threads.h
* Most Unixen can also be told to use threads.h for
developer/conformance testing
If we do commit v3-0003, we have three implementations and we get:
* Unixen, Windows/MinGW = pthread.h
* Windows/MSVS = windows.h
* Most Unixen + Windows/VS can also be told to use threads.h for
developer/conformance testing
> I'm looking at some other patch sets that are fiddling with threads and
> the API layers, and I'm wondering if it's worth proceeding with those,
> or rather focus on getting this patch set done and then rebase those
> other ones on top of this new API.
I still need to think about Jakub's recent feedback, but once I've
done that, and once we have a decision on v3-0003, I think something
like 0001-0008 should be about ready to commit?
Then looking at the higher numbered patches, I wonder if anyone has
any comments on these ideas for (IMHO) improving some of the nastier
cleanup programs we deal with in frontend programs on ^C:
* v3-0010 is way for frontend programs to run their cleanup handler in
a thread, ie more like Windows
* v3-0011 is a way for such a handler to clean up a set of connections
I need to compare Bryan's work on frontend thread architecture and see
if my (competing) proposals for the same programs are redundant
(assuming he's rebased on pg_threads.h that we hopefully commit soon),
and/or whether my 0010/0011 stuff is useful/relevant or he had better
idea, etc...
Re: pg_threads.h take II
От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Wed, Nov 11, 2026 at 11:14 AM Thomas Munro wrote: > I still need to think about Jakub's recent feedback, but once I've > done that, and once we have a decision on v3-0003, I think something > like 0001-0008 should be about ready to commit? Hey Thomas, I hope you don't mind that I've tried to update your patches a bit. I'm very interested in seeing this work eventually merged so I thought I'd pitch in a bit. v3 no longer applies (cfbot has shown it red since October), so here is v4: a rebase, Jakub's feedback, a proposal for v3-0003, and fixes for some bugs that turned up in testing. Your twelve patches are all here under your name, unchanged apart from the rebase and one fix to 0002, described below. Everything I added is a separate patch placed right after the one it touches, so you can squash or drop each one. The one change to your 0002: it didn't compile on its own, because pg_mtx_init_impl() calls pg_mtx_validate_type(), which only arrived with the Windows mapping. I moved that function and its rwlock twin into 0002, so that every patch in the series builds. The new patches: 0003 fixes bugs in 0002. pg_mtx_recursive mapped to the plain type (Jakub's point 2). On POSIX, pg_thrd_barrier_wait() reported an error to one waiter in every round, because pthread_barrier_wait() returns PTHREAD_BARRIER_SERIAL_THREAD to that waiter; pgbench ignores the result, which is why nobody noticed. The error detail was formatted with strerror(), but that is pg_strerror(), with a static buffer, so two threads failing at once raced on it; it now uses strerror_r(). Also a missing va_end(), and two macros that expanded to names no implementation defines (PG_TSS_DTOR_ITERATIONS and PG_RWLOCK_PLAIN_INIT). 0004 is Jakub's error-checking mutexes for assertion-enabled builds, plus an answer to his question 3b: pg_mtx_lock() and pg_mtx_unlock() now assert success themselves. Only 4 of the 36 lock and unlock calls in the tree check the result, so otherwise an EDEADLK would just be ignored. Statically initialized mutexes are only checked on glibc, since PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP is a glibc extension. 0005 adds src/test/modules/test_pg_threads, a standalone program run as a TAP test. It checks behavior rather than implementation details (create and join, detach, the three mutex types, condition variables, call_once, tss destructors, barriers, rwlocks, error strings), so the same test covers all three mappings. Against v3-0002 it fails the recursive-mutex and barrier checks. Built with PG_THREADS_USE_WINDOWS_H, it also found a bug in the native Windows mapping. 0007 fixes that bug and one other in the native Windows mapping. SleepConditionVariable*() fail with ERROR_TIMEOUT, but pg_thrd_map_windows_error() only knew WAIT_TIMEOUT, so pg_cnd_timedwait() reported a timeout as an error. And pg_tss_ensure_fls_registered() read pg_tss_fls without the lock and returned an uninitialized result if FlsAlloc() failed; it now uses pg_call_once(). 0008 is about v3-0003, which you asked about. I'd keep 0003 and go one step further: use the native mapping for MSVC too, so that is only ever chosen by PG_THREADS_USE_THREADS_H, for conformance testing. With v3's selection only MinGW used 0003, and MinGW binaries load libwinpthread-1.dll anyway through the gcc runtime, so there it bought nothing. Using it for MSVC means MSVC builds don't depend on vcruntime140_threads.dll, which would otherwise have to be redistributed with PostgreSQL, and leaves one Windows implementation instead of two to keep in agreement. The cost is that we own that code, which is what test_pg_threads is for. We also lose pg_mtx_timed on MSVC, which Visual Studio's mtx_t has, but nothing uses it. 0013 makes pgbench report thread errors with pg_thrd_error_string_with_detail(). It assigned the pg_thrd_* result to errno and printed %m, so a generic failure came out as "Interrupted system call". 0016 is Jakub's point 5. The pg_basebackup flag that the WAL streamer sets and the main thread polls was a volatile bool, which is a data race between threads, and sig_atomic_t wouldn't help, since it only promises atomicity against a signal handler interrupting the same thread. Until frontend code can use atomics, a mutex seemed the smallest correct fix; the same file already does that for xlogendptr. 0017 is Jakub's point 1, pg_thrd_setname(const char *name) in pg_threads_ext.h. It names only the calling thread, because macOS can't name another one, and it is best-effort and reports nothing. On Windows it uses SetThreadDescription(), and test_pg_threads reads the name back there and on Linux. I kept it out of pg_thrd_create() so that pg_threads.h stays a faithful copy of . pgbench names its worker threads and pg_basebackup its WAL streamer; main threads are left alone, since on Linux naming the main thread renames the process in ps. I didn't add Jakub's point 6, pg_thrd_init(): pg_call_once() covers lazy setup, and libpq and ecpg can't count on their callers to call an init function. 0021 fixes the pg_dump/011_restore failure at 0020. On Unix, _ReopenArchive() closed the original FILE before reopening it, and only skipped that on Windows, where the workers were already threads sharing the leader's FILE through the cloned ArchiveHandle. With threads everywhere, the first worker closed the file under the others, and "pg_restore -j2" of a custom-format archive failed or hung. Bryan, your v2 series has the same problem: I rebased it onto this branch, and with this change all of the pg_dump TAP tests pass. About 0018-0020: as I read it, 0020 removes fork() but keeps the pipes and the string protocol, while Bryan's v2-0004 and v2-0005 replace those with an in-memory channel and struct commands, so on transport his series supersedes 0020. 0018 (pg_signal_processor) and 0019 (cancel_set) are about something else, namely where ^C cleanup runs, and Bryan's series doesn't change that: it keeps the async-signal-safe handler on Unix and the console handler on Windows. The two seem to fit together, with cancel_set as the set of connections that his handle_async_cancellation() walks today. I've kept 0018-0020 as they were, plus the fix, so that the series stays green. Testing, at the tip unless noted: * every patch builds with -Werror and assertions on Linux x86_64, and test_pg_threads passes at each patch that has it * full meson test on Debian 13, x86_64 and aarch64, with assertions: 377 ok, 53 skipped, no failures * Linux with PG_THREADS_USE_THREADS_H defined: the suites of all the thread users, and regress, pass * FreeBSD 15.1, clang 19: builds with -Werror, and the same suites pass; the thread names show up in procstat -t * riscv64 Linux: builds with -Werror; ecpg and test_pg_threads pass * Windows 11 arm64, MSVC 19.51: builds, and test_pg_threads, ecpg, pg_dump, and regress pass. The libpq, pg_basebackup, and pgbench TAP tests fail on that machine with plain master too, so I haven't counted them. The binaries import nothing from vcruntime140_threads.dll, and pgbench's and pg_basebackup's thread names show up through GetThreadDescription(). * test_pg_threads built for both the and mappings, on arm64 and on native x64 Windows, and the mingw-w64 UCRT cross-build (as in the CompilerWarnings CI task), run on native x64 * GitHub Actions with the in-tree workflow: all jobs pass (Linux autoconf and meson 32- and 64-bit, macOS, Windows with Visual Studio and with MinGW, CompilerWarnings, SanityCheck) best. -greg [0] https://github.com/gburd/postgres/tree/thomas/thr
Re: pg_threads.h take II
От:
Andreas Karlsson <andreas@proxel.se>
Дата:
Hi, I do do not know if it happens to just me but your mail client/script for sending emails seem to be broken as this message started a new thread in Thunderbird and it seems to only be (some of) your messages which does this. Anyone else seeing the same? -- Andreas Karlsson Percona
Re: pg_threads.h take II
От:
Greg Burd <greg@burd.me>
Дата:
On Sun, Nov 15, 2026 at 12:06:04AM +0100, Andreas Karlsson wrote: >Hi, Hey Andreas, >I do do not know if it happens to just me but your mail client/script >for sending emails seem to be broken as this message started a new >thread in Thunderbird and it seems to only be (some of) your messages >which does this. Yikes, yes indeed there is a problem. I'm not scripting replies, there's no agent emailing for me but I have switched to a new email provider and to a new client (neomutt). >Anyone else seeing the same? When I review the threads I see it too. I'll fix it. >-- >Andreas Karlsson >Percona -greg