Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 7f40c15ed2613ba8846c93938407559089ded57b65c9ac9f2babe3ae300d1fc7
Ticket: 893f8cc5db3ba8bd6bed80ce89a0a75c6088a37c
Nested mutexes following TIP 509
User & Date: apnadkarni on 2025-09-18 05:37:52
Changes

  1. icomment:
    I confirmed that Windows native condition variables also only work when the critical section lock is held exactly once so Christian's changes are appropriate for Windows as well.
    
    However, now having looked at the recursive implementation for POSIX (which is essentially now cloned for Windows), I am not convinced the implementation is correct in the first place (i.e. before Christian's changes).
    
    Consider the lock function:
    
    ```
    static void
    PMutexLock(
        PMutex *pmutexPtr)
    {
        if (pmutexPtr->thread != pthread_self() || pmutexPtr->counter == 0) {
    	pthread_mutex_lock(&pmutexPtr->mutex);
    	pmutexPtr->thread = pthread_self();
    	pmutexPtr->counter = 0;
        }
        pmutexPtr->counter++;
    }
    ```
    
    I am no expert on architectures, but I am pretty sure accessing the thread and counter fields outside of any locks or memory barriers can result in stale values being read with the caller erroneously thinking it is holding the lock when it isn't and foregoing executing the `pthread_mutex_lock`.
    
    The equivalent code on Windows (added by Christian) is
    
    ```
        if (wmPtr->thread != Tcl_GetCurrentThread() || wmPtr->counter == 0) {
    	EnterCriticalSection(&wmPtr->crit);
    	wmPtr->thread = Tcl_GetCurrentThread();
    	wmPtr->counter = 0;
        }
        wmPtr->counter++;
    ```
    
    and suffers from the same issue.
    
    On Windows, the fix should be simple by moving the EnterCriticalSection above the `if` statement since critical sections can be recursively locked. This is not possible on POSIX for obvious chicken and egg reasons as the mutex is not recursively lockable.
    
    A possible solution is to add another internal mutex to the mutex wrapper that controls access to the counter and thread but that needs deeper thought to determine whether it is indeed a fix and does not cause problems of its own.
    
    This gets back to Sergey's comment about implementing synchronization mechanisms being dicey and even if the above suggested additional mutex is deemed to work, we should explore eliminating recursive mutexes.
    
    As an example, it was only a few years ago that I learnt that the double locking idiom that I had long presumed was safe (and is in fact extensively used in Tcl) in fact has race conditions on some architectures and platforms (thankfully, I *think* not on x86 or ARM).
    
  2. login: "apnadkarni"
  3. mimetype: "text/x-markdown"