[PATCH v2] Cygwin: pthread: Fix a race issue introduced by the commit 2c5433e5da82

Bruno Haible bruno@clisp.org
Thu May 30 08:47:38 GMT 2024


Noel Grandin wrote in cygwin-patches:
> Pardon my ignorance, but why not rather use the Windows SRWLock functionality?
> https://learn.microsoft.com/en-us/windows/win32/sync/slim-reader-writer--srw--locks
> 
> SRW locks are very fast, only require a single pointer-sized storage area, can be statically initialised, and do not 
> need to be destroyed, so there is no possibibilty of memory leakage.
> 
> Then the implementation simply becomes
> 
> int pthread::once (pthread_once_t *once_control, void (*init_routine) (void))
> {
>      AcquireSRWLockExclusive(once_control->lock);
>      if (!once_control->state)
>      {
>          init_routine()
>          once_control->state = 1;
>      }
>      ReleaseSRWLockExclusive(once_control->lock);
> }

SRW locks are spin-locks. Since they are only pointer-sized,
ReleaseSRWLockExclusive cannot notify other threads — unlike CRITICAL_SECTION.
Therefore, AcquireSRWLockExclusive must busy-loop when the lock is already
held.

But busy-looping is a bad practice for pthread_once. In the case,
for example, that the init_routine reads a multi-megabyte data
structure into memory and parses it, the other threads that wait
on the result of this operation would by busy-looping, eating
full CPU time.

Bruno





More information about the Cygwin mailing list