LIU Hao wrote:

>> There is an easier approach: attempt to recursively lock the mutex before 
>> unlocking it. This however
>> introduces another issue - it is possible that we will obtain ownership for 
>> an abandoned mutex. My
>> solution for this is to introduce new value for `mutex->State`, which will 
>> be checked for in `*Lock` and
>> `*TryLock` causing them to report `EOWNERDEAD` condition.

My idea is that in such case, `*Unlock` fails with `EPERM`, while sets 
`mutex->State` to `OwnerDied` and releases the mutex. The next thread gains the 
ownership of the mutex will change `OwnerDied` to `Inconsistent` and return 
`EOWNERDEAD`.

> Is it required for a robust mutex to detect unpaired calls to 
> `pthread_mutex_unlock()`? And AFAICS that's
> the only error condition.

POSIX specification[1] says that all robust mutexes must return an error code 
when a thread attempts to unlock mutex it does not own (I would include an 
unlocked mutex into this category).

Unfortunately, it does not specify behavior when state protected by a 
[recursive] mutex is inconsistent, and thread attempts to recursively 
lock/unlock it.

>> I propose the following:
>>
>> 1. We improve handling of mutex ownership using recursive locking.
>> 2. We keep recursive lock count in user mode.
>
> This makes sense.
>
> To me it looks like `pthread_mutex_lock()` should always call 
> `WaitForSingleObject()` and increment the
> user-mode counter which should be kept in sync with the kernel-mode one.

Yes, we can do this. With change 1, this already what they will do; my idea was 
to immediately call `ReleaseMutex` if we detect that mutex is being locked 
recursively, keeping kernel-mode lock count at 1 all the time.

It seems like `GetLastError` returns `ERROR_MUTANT_LIMIT_EXCEEDED` when 
`WaitForSingleObject` fails because recursive lock count has been exceeded. So, 
we should be able to fail with `EAGAIN` when kernel-mode lock count has reached 
its limit.

- Kirill Makurin

[1] 
https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/pthread_mutex_lock.html

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

Reply via email to