title: how to check whether pthread_mutex_t is locked or not
body: <p>Am quite sure this is a naive question but still going to ask it nevertheless since I couldn't find much help on net. I am writing a c++ code using pthreads . The following is an outline of one of the methods</p>
  
  <pre><code>void Method1()
  {
      try
      {
      pthread_mutex_lock(&amp;syncLock);
      statement1;
      statement2;
      pthread_mutex_unlock(&amp;syncLock);
      statement3;
      statement4;
      }
      catch(exception&amp; e)
      {
      log error
      }
  }
  </code></pre>
  
  <p>where syncLock is of type <code>pthread_mutex_t</code> and is initialized using the default initialization. </p>
  
  <p>My question is that if an exception is thrown in the statement2 of the method then the control passes directly to the catch statement. In that case my mutex remains locked. But I also cant simply write an unlock statement in the catch block since if the exception came from statement 3 then the mutex has been unlocked and calling unlock on an already unlocked mutex results in undefined behavior.</p>
  
  <p>So is there a way I can check whether the mutex has been unlocked or not in the catch statement. Or, is there a C# style lock statement alternative available in c++ so I am sure that the lock is released even if an exception is thrown from within that block </p>
  
  <p>I am not inclined to use libraries for this purpose. A simple custom solution will be much appreciated</p>
  
  <p>Thanks</p>