Re: Can we get rid of TerminateThread() in pg_dump?

Thomas Munro <thomas.munro@gmail.com>

From: Thomas Munro <thomas.munro@gmail.com>
To: Jelte Fennema-Nio <postgres@jeltef.nl>
Cc: Bryan Green <dbryan.green@gmail.com>, Heikki Linnakangas <hlinnaka@iki.fi>, pgsql-hackers <pgsql-hackers@postgresql.org>, Tom Lane <tgl@sss.pgh.pa.us>, Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: 2026-07-05T05:03:08Z
Lists: pgsql-hackers
On Sat, Jul 4, 2026 at 11:15 PM Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> On Sat, 4 Jul 2026 at 02:51, Thomas Munro <thomas.munro@gmail.com> wrote:
> > We don't actually care about the threads
> > themselves, and it doesn't seem that great if we have to introduce an
> > IPC ping-pong of some kind with each thread.
>
> Agreed. But I do agree with Heikki that swapping out stderr seems pretty
> hacky. At the very least because now the main thread cannot write to
> stderr either anymore (which is why you removed the "terminated by user"
> write I guess).
>
> How about instead we do something like the attached?

That's definitely nicer, if we know that all potential error logging
caused by cancellation happens in a context that can check the flag.

I didn't even look into that, because I was deliberately trying to
avoid needing atomics from here, because I need this to work on Unix
too, and I didn't want to open too many cans of worms at the same
time.  Hence the appeal of a simple async-signal-safe system call that
has the right concurrency properties already and works also on Windows
without a separate code path.  But... reaching for the can opener...

1. If we're ready to drop VS < 2022 and GCC < 4.9, we could just use
<stdatomic.h> directly in frontend code (independently of the project
to use it in the backend).
2. If we're not ready yet we could make "port/atomics.h" or selected
parts of it frontend-allowed.
3. Maybe all we really need for this case is memory barriers, and we
could move those out to a frontend-allowed header.

> To be clear, I do think we should stop using TerminateThread because I
> wanna replace PQcancel there with PQcancelBlocking[1] PQcancelBlocking
> does a whole TLS handshake, which is almost certainly taking some locks.
>
> Note that the way to achieve that I moved the Ctrl+C handler to a
> dedicated thread on Unix too, so it starts behaving the same as Windows
> in that respect. I think combined with you changing pg_dump to use
> worker *threads* on Unix too, we would then get pretty much identical
> behaviour across OSes for pg_dump.

I wondered about something like this too.  Nice Unix/Windows
convergence, and it sounds like you have no other choice if you want
to do fancy non-async-signal-safe footwork.



Commits

  1. Redesign handling of SIGTERM/control-C in parallel pg_dump/pg_restore.