title: c++ correct use of mutex
body: <p>i have multithreaded project and i've run it through valgrind with --tool=helgrind and it showed me few errors. I'm using mutex there exaxtly how i found on the net how to use it, can you please show me whats wrong?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;pthread.h&gt;
  
  #define MAX_THREADS     100
  #define MAX_SESSIONS    100
  
  static pthread_mutex_t  M_CREATE_SESSION_LOCK= PTHREAD_MUTEX_INITIALIZER;
  
  
  .....
  
  
  
  void connection::proccess(threadVarsType &amp;THREAD) {
      ....
  
      pthread_mutex_lock(&amp;M_CREATE_SESSION_LOCK);
  
      unsigned int ii;
      for (ii=0; ii&lt;MAX_SESSIONS; ii++) {
          if (SESSION[ii]==NULL) {
              break;
          }
      }
      if (ii==MAX_SESSIONS-1) {
          ....
          pthread_mutex_unlock(&amp;M_CREATE_SESSION_LOCK);                       // unlock session mutex
          ....
          return;
      } else {
          ....
          pthread_mutex_unlock(&amp;M_CREATE_SESSION_LOCK);                       // unlock session mutex
          ....
      }
  
      ....
  }
  </code></pre>
  
  <p>and the error messages:</p>
  
  <pre><code>==4985== Thread #1's call to pthread_mutex_lock failed
  ==4985==    with error code 22 (EINVAL: Invalid argument)
      ....
  ==4985== Thread #1 unlocked an invalid lock at 0x4E7B40
  ==4985==    at 0x32CD8: pthread_mutex_unlock (hg_intercepts.c:610)
      ....
  ==4985== Thread #1's call to pthread_mutex_unlock failed
  ==4985==    with error code 22 (EINVAL: Invalid argument)
      ....
  ==4985== Thread #1's call to pthread_mutex_lock failed
  ==4985==    with error code 22 (EINVAL: Invalid argument)
      ....
  ==4985== Thread #1 unlocked an invalid lock at 0x4E7B40
  ==4985==    at 0x32CD8: pthread_mutex_unlock (hg_intercepts.c:610)
      ....
  ==4985== Thread #1's call to pthread_mutex_unlock failed
  ==4985==    with error code 22 (EINVAL: Invalid argument)
  </code></pre>