On Friday, October 30th, 2026 at 5:48 PM, Luca Bacci <[email protected]> 
wrote:

> A few updates on this:
> 
> We can't really set the event from the the safe part of unlock() (I call
> "safe" the part of unlock() before the state reset to UNLOCKED). Setting
> the event early is clearly prone to deadlock! To make things safe we can:
> 
>  1. Add a count for users in the critical part of unlock() (I call
>     "critical" the part of unlock() after the state reset to UNLOCKED)

Can we just have an extra field which would be 0 when there are no threads
in the "critical" part of any operation and 1 when there are.

Before setting state to `Unlocked`, the thread would `InterlockedIncrement` it;
just before returning it would `InterlockedDecrement` it. With this, destroy()
could spin until it becomes zero, and only then close the event handle.

I think the spin duration should be very brief and should only occur when
destroy() is in race with unlock().

>  2. Add something like hazard pointers: every thread has a slot
>     indicating if it's running the critical part for a specific mutex.
> 
> Then destroy() has to synchronize with threads in unlock(). Turn out we
> can't use the main event of the mutex however. What we can do:
> 
>  1. Spin wait within destroy(). Since we can't fall back to a proper
>     wait, we have to spin indefinitely. In this case we should
>     interleave calls to SwitchToThread, Sleep(0), Sleep(1).
>  2. Use a dedicated event. We can use another event to synchronize
>     unlock() and destroy(). Fortunately we don't have to allocate this
>     event upfront; instead the event can be allocated on-the-fly.

I hope we can avoid using more than one synchronization object in order to
implement a mutex. We use them internally, including as part of implementation
for other synchronization objects.

Take `pthread_cont_t` for example; it use two semaphores and three critical 
sections
(which are, if I recall correctly, are implemented using semaphores). Insanity!

I have prepared a change which replaces use of critical sections with 
`pthread_mutex_t`.
If we were to take this approach, total number of synchronization objects used 
to implement
`pthread_cont_t` would increase from 5 to 8. Even more insane!

> If we go with option 2) we can also use the WaitOnAddress emulation that
> I developed for pthread_once.

- Kirill Makurin


_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to