Re: [PATCH v1] Fix races in Windows pthread emulation

From: Nazir Bilal Yavuz <byavuz81(at)gmail(dot)com>
To: Harrison Booth <harrisontbooth(at)gmail(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: [PATCH v1] Fix races in Windows pthread emulation
Date: 2026-08-20 12:09:19
Message-ID: CAN55FZ2_z-FuntouobNzgn9CXNJ1S_BciOHEOL6fTv8C_00JEw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

Thank you for working on this!

On Fri, 24 Jul 2026 at 10:07, Harrison Booth <harrisontbooth(at)gmail(dot)com> wrote:
>
> On native Windows ARM64, the ECPG thread/alloc test could hang until
> Meson's 1000-second timeout. The cause was a race in the Windows pthread
> mutex emulation.

I ran into this exact issue today [1] and found your thread.

> The mutex initialization path used InterlockedExchange to set initstate to
> 2. A waiting thread could therefore change the fully initialized state from
> 1 back to 2. pthread_mutex_unlock would then see a state other than 1,
> return EINVAL, and leave the critical section locked.

I tried to understand the problem and the related Windows thread
functions, please correct my understanding:

1- In pthread_mutex_lock(), calling
InterlockedExchange(&mp->initstate, 2) writes unconditionally,
clobbering an initialized state 1 back to 2.
2- The thread enters the critical section while mp->initstate = 2.
3- Later, when pthread_mutex_unlock() is called, if (mp->initstate !=
1) evaluates to true, causing the function to return EINVAL without
releasing the underlying critical section, leading to a deadlock.

And your patch fixes this problem with
InterlockedCompareExchange(&mp->initstate, 2, 0), because now you
check the initial value so that you can't overwrite 1 with 2.

[1] https://github.com/nbyavuz/postgres/actions/runs/32351446950/job/96371608653

--
Regards,
Nazir Bilal Yavuz
Microsoft

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Ashutosh Sharma 2026-08-20 12:25:59 Re: Report bytes and transactions actually sent downtream
Previous Message Etsuro Fujita 2026-08-20 11:55:57 Re: Further cleanup related to statistics import support in postgres_fdw