在 2026-9-24 09:03, Kirill Makurin 写道:
This approach works with a few minor complications.In original changes, when unlocking the mutex, we would update `mutex->State` before calling `ReleaseMutex`. We need to do this so that unblocked threads could detect and propagate some error conditions. However, with this approach we should update this information only before unblocking the waiting thread.My first thought was to use an event (although, using two sync objects in order to implement a mutex feels like total overkill to me) with logic like this:1. Before trying to unlock the mutex, reset the event 2. Call `ReleaseMutex`; if call succeeds, the unblocked thread waits for the event to be signaled 3. Only if 2 succeeds, update `mutex->Owner` and `mutex->State` 4. Signal the event so unblocked thread can see the changesThe issue is that if current thread terminates after 1 and before 4, it would deadlock all threads trying to lock the mutex.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.
Is it required for a robust mutex to detect unpaired calls to `pthread_mutex_unlock()`? And AFAICS that's the only error condition.
This gets messy.Mutex type-specific `*TryLock` accepts second `BOOL` argument; when `TRUE` it only succeeds when mutex is not owned by any thread, for recursive mutexes this includes the calling thread. It is used by `pthread_mutex_destroy` to prevent (fail with `EBUSY`) destruction of a locked mutex.We need both lock count and thread ID for this.Storing only thread ID is not sufficient to handle this: when unlocking, we cannot set `mutex->Owner` to `THREAD_ID_NO_OWNER` because we don't know the lock count, which in turn makes checking `mutex->Owner` in `*TryLock` unreliable.Also, we may mark protected state as unrecoverable while a thread still has recursive lock on a mutex. Owning still needs to recursively unlock the mutex, but attempts to recursively lock it will fail with `ENOTRECOVERABLE`. IMO, current behavior makes more sense.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.
-- Best regards, LIU Hao
OpenPGP_signature.asc
Description: OpenPGP digital signature
_______________________________________________ Mingw-w64-public mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/mingw-w64-public
