title: Linux: How can I find the thread which holds a particular lock?
body: <p>I have a multi-threads program which is running on Linux, sometimes if I run gstack against it, there is a thread was waiting for a lock for a long time(say, 2-3 minutes), </p>
  
  <blockquote>
    <p>Thread 2 (Thread 0x5e502b90 (LWP 19853)):</p>
    
    <p>0  0x40000410 in __kernel_vsyscall ()</p>
    
    <p>1  0x400157b9 in __lll_lock_wait () from /lib/i686/nosegneg/libpthread.so.0</p>
    
    <p>2  0x40010e1d in _L_lock_981 () from /lib/i686/nosegneg/libpthread.so.0</p>
    
    <p>3  0x40010d3b in pthread_mutex_lock () from /lib/i686/nosegneg/libpthread.so.0</p>
    
    <p>...</p>
  </blockquote>
  
  <p>I checked the rest of the threads, none of them were taking this lock, however, after a while this thread (LWP 19853) could acquire this lock successfully.</p>
  
  <p>There should exist one thread that had already acquired this lock, but I failed to find it, is there anything I missing?</p>
  
  <p>EDIT:
  The definition of the pthread_mutex_t:</p>
  
  <blockquote>
    <p>typedef union</p>
    
    <p>{</p>
    
    <p>struct __pthread_mutex_s
     {</p>
    
    <p>int __lock;</p>
    
    <p>unsigned int __count;</p>
    
    <p>int __owner;</p>
    
    <p>/* KIND must stay at this position in the structure to maintain
          binary compatibility.  */</p>
    
    <p>int __kind;</p>
    
    <p>unsigned int __nusers;</p>
    
    <p><strong>extension</strong> union
       {
         int __spins;
         __pthread_slist_t __list;
       };</p>
    
    <p>} __data;</p>
    
    <p>char _<em>size[</em>_SIZEOF_PTHREAD_MUTEX_T];</p>
    
    <p>long int __align;</p>
    
    <p>} pthread_mutex_t;  </p>
  </blockquote>
  
  <p>There is a member "__owner", it is the id of the thread who is holding the mutex now.</p>