title: How do I determine if a thread has a lock?
body: <p>I am writing an Objective-C class that I want to be thread safe. To do this I am using pthreads and a <code>pthread_rwlock</code> (using <code>@synchronized</code> is overkill and I want to learn a bit more about pthreads). The lock is inited in the objects designated <code>init</code> method and destroyed in <code>dealloc</code>. I have three methods for manipulating the lock; <code>readLock</code>, <code>writeLock</code>, <code>unlock</code>. These three methods simply invoke the related pthread functions and currently nothing else.</p>
  
  <p>Here are two of the objects methods, both of which require a writeLock:</p>
  
  <pre><code>-(void)addValue:(const void *)buffer
  {
      [self writeLock];
  
      NSUInteger lastIndex = self.lastIndex;
      [self setValue:buffer atIndex:(lastIndex == NSNotFound) ? 0 : lastIndex+1];
  
      [self unlock];
  }
  
  
  -(void)setValue:(const void *)buffer atIndex:(NSUInteger)index
  {
      [self writeLock];
      //do work here
      [self unlock];
  }
  </code></pre>
  
  <p>Invoking <code>setAddValue:</code> will first obtain a write lock and then invoke <code>setValue:atIndex:</code> which will also attempt to obtain a write lock. The documentation states that the behaviour is undefined when this occurs. Therefore, how do I check if a thread has a lock before attempting to obtain a lock? </p>
  
  <p>(I could ensure that critical section make no invocation that trigger another lock request, but that would mean code repetition and I want to keep my code DRY).</p>