title: Check if pthread_mutex is initialized
body: <p>Using pthreads it mandatory to call pthread_mutex_init() on any mutex before obtaining the lock.</p>
  
  <p>According to POSIX the locking an uninitialized mutex is only defined for mutex with priority protection (<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html" rel="noreferrer">opengroup : pthread_mutex_lock</a>)</p>
  
  <p>According to the manpage <a href="http://www.linuxmanpages.com/man3/pthread_mutex_lock.3thr.php" rel="noreferrer">pthread_mutex_lock.3thr</a> it should return EINVAL if called on an uninitalized mutex.
  Assuming portability is not an issue, would it be valid (a good idea?) to write code like:</p>
  
  <pre><code>pthread_mutex_t lock;
  
  int ret = pthread_mutex_lock(&amp;lock);
  if (ret != 0){  
      if(ret == EINVAL){
          pthread_mutex_init(&amp;lock, NULL);
      } else {
        /* other error */
      }
  } 
  </code></pre>
  
  <p>Is there another way to check if a pthread_mutex has been initialized?</p>
  
  <p>The whole scenario is part of a library (by politics unfortunately not C++) and I want to avoid to the maximum wrong usage. I.e. A client may initialize the object created twice, may pass the object to other functions before properly initialize it etc. </p>
  
  <p>Currently there is an aditional flag in the object that marks if the mutex has been initialized, I was wondereing if this is really necessary.</p>
  
  <p>Looking at the expansion of the macro <code>PTHREAD_MUTEX_INITIALIZER</code> for static mutex initialization it just expands into a struct with all members set to 0. 
  Can I assume that is not required to call mutex_destroy if it is no longer required, given the ressource itself is freed (sure if noone else uses it)?</p>
  
  <p><strong>Update:
  Jens' answer is absolutely correct</strong>. The following program yields completely undefined behavior:</p>
  
  <pre><code>int main(int argc, char** argv)
  {
  
  pthread_mutex_t lock;
  int ret = pthread_mutex_lock(&amp;lock);
  if (ret != 0) {
      printf(" ERR : %d %s \n", ret, strerror(ret));
      if (ret == EINVAL) {
          pthread_mutex_init(&amp;lock, NULL);
      }
  } else {
      printf(" ok \n");
  }
  pthread_mutex_unlock(&amp;lock);
  return 0;
  }
  </code></pre>
  
  <p>Sometimes it deadlocks, somtimes it prints o.k. .....</p>