I wrote:
> LIU Hao wrote:
>
>> Yes, there's an edge case that the identifier of the dead owner gets reused
>> for the calling thread.
>>
>> This lock-unlock-unlock pattern looks a bit tricky. You can also prevent the
>> race condition by protecting
>> the internal state with a critical section:
>>
>> pthread_mutex_lock(pthread_mutex_t* m)
>> {
>> // ...
>> EnterCriticalSection(&m->state_cs);
>> WaitForSingleObject(m->mutex, timeout);
>> LeaveCriticalSection(&m->state_cs);
>> }
>>
>> pthread_mutex_unlock(pthread_mutex_t* m)
>> {
>> // ...
>> EnterCriticalSection(&m->state_cs);
>> ReleaseMutex(m->mutex);
>> LeaveCriticalSection(&m->state_cs);
>> }
>
> The issue with using critical section or any other synchronization object for
> this purpose is that if thread terminates while owning it, it will likely
> deadlock other threads trying to use this mutex. Recursive locking solves
> this issue: if thread terminates while owning (possibly recursive) lock, the
> next thread will be notified with `WaitForSingleObject` returning
> `WAIT_ABANDONED`.
In one of my previous messages, I also mentioned that I wanted to use an event
for the same purpose and given an example of how it may be problematic. I still
think that using the fact that Windows mutexes are recursive is our best
solution.
About `CRITICAL_SECTION`. While I was writing changes for spinlock.c and
mutex.c, I looked at file history and saw that in the past both spinlocks and
mutexes were basically wrappers around critical sections.
I understand that critical sections are very easy to use. However, my opinion
is that winpthreads should not use them at all. There are at least the
following reasons:
1. Function `TryEnterCriticalSection` is only available since NT 4.0 and Win98.
We would have to lookup it up at runtime, and use a fallback if it is not
available. winpthreads still uses critical sections to implement
`pthread_cond_t`. I think we can simply use `pthread_spinlock_t` instead of
critical sections, or completely update implementation.
I plan to take care of this later.
2. While `InitializeCriticalSection` does not return a value, according to its
documentation[1], it may raise `STATUS_NO_MEMORY ` exception on pre-Vista under
low memory conditions.
All real-world uses of critical sections I have seen so far never handle this
case.
> Maybe we could use another mutex for this, but it feels like overkill to me.
Also, it would make general logic noticeably more complicated.
- Kirill Makurin
[1]
https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsection
_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public