title: The calling sequence of pthread_init pthread_lock, pthread_destroy and so on?
body: <p>Normally, the correct sequence is something like this:</p>
  
  <pre><code>pthread_mutex_init(&amp;mutex,NULL);
  
  pthread_mutex_lock(&amp;mutex);
  
  pthread_mutex_unlock(&amp;mutex);
  
  pthread_mutex_destroy(&amp;mutex);
  </code></pre>
  
  <p><code>mutex</code> should be initialized first, and then <code>pthread_mutex_lock</code> and <code>pthread_mutex_unlock</code> can be called in respective thread to protect the critical section, finally <code>pthread_mutex_destroy</code> is called to destroy the <code>mutex</code> after the completion of all threads.  But if the order is mixed, What would happend?</p>
  
  <p>I disrupt the sequence of the functions  in order to find out the error, but everything seems normal when the sequence is messed in different way. Here is an example.</p>
  
  <pre><code>pthread_mutex_t mutex;
  static int count = 0;
  
  void* func(void* arg)
  {
      pthread_mutex_lock(&amp;mutex);
      *(int*)arg = *(int*)(arg) + 1;
      printf("thread %d\n", *(int*)arg);
      pthread_mutex_unlock(&amp;mutex);
  }
  
  int main(int argc, char* argv[])
  {
      int i;
      pthread_mutex_init(&amp;mutex, NULL);
  
      pthread_mutex_destroy(&amp;mutex);
  
      for(i = 0; i &lt; 3; i++)
      {
          pthread_t tid;
          pthread_create(&amp;tid, NULL, func, (void*)(&amp;count));
          sleep(5);
      }
  
      printf("the main thread exit normally.\n");
  }
  </code></pre>
  
  <p>I want to ask whether the sequence matters to the program. Is there something inside the function to assure the calling sequence, or something else?  If these functions can be used without order, why should <code>pthread_mutex_init()</code> and <code>pthread_mutex_destroy()</code> be defined?</p>