title: PThread RWLock Deadlocking with Recursive Locks
body: <p>I've been working on a small sand-boxed example to help me figure out how to use rwlocks. Everything seems fairly straightforward, however I'm getting deadlocks in my example every once and a while and don't understand why it's happening.</p>
  
  <p>I've put the code example on pastebin because it's more than a few lines of code: <a href="http://pastebin.org/359203" rel="nofollow">http://pastebin.org/359203</a></p>
  
  <p>If you run the example. When it eventually deadlocks the last three print statements will be one of two cases:</p>
  
  <p>one:</p>
  
  <pre><code>th4: request lock
  th3: request lock
  th4: locked
  </code></pre>
  
  <p>two:</p>
  
  <pre><code>th3: request lock
  th4: request lock
  th3: locked
  </code></pre>
  
  <p>Based on the output. To me it seems like there is an eventual deadlock from a second call to a locking function, whether it's to a read lock, or a write lock. But since one of the threads has the lock, and the same thread is what calls the second locking function, why is it deadlocking? Even more interesting, what is it in this small case that is causing the deadlock?</p>
  
  <p>Note that I'm on Mac OS X, and that this is a seriously contrived example. It's sand-boxed from something else I'm working on and wanted to make sure I get this part right.</p>