title: Can a race condition occur between mutex unlocking and returning from function
body: <p>I've been learning about Multithreaded applications and in particular, about how a mutex can be used to prevent race conditions. However, while writing some code, I discovered a race condition (using the <code>helgrind</code> tool from <code>valgrind</code>) in my code, I believe that execution in one thread may be pausing after the unlock and before the return.</p>
  
  <p>If we take the example code below, <strong>is a race condition possible in between the mutex unlock and the return statement? If so, how do we get around this   problem?</strong> (short of requiring the caller to pass in some sort of buffer and returning a constant value like <code>0</code>)</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  
  int x = 0;
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  
  doSomething()
  {
      pthread_mutex_lock(&amp;mutex);
      ++x;
      pthread_mutex_unlock(&amp;mutex);
                 /* &lt;-- Race Condition? */
      return x;
  }
  
  void *t2()
  {
      doSomething();
  }
  
  main()
  {
      pthread_t thread;
      pthread_t_create(&amp;thread, NULL);
      doSomething();
      pthread_join(thread, NULL);
      return 0;
  }
  </code></pre>
  
  <p><strong>NOTE:</strong> I understand that in the above example, returning 'x' is useless, as x is global. However, in a library where 'x' needs to be global for library functions, but can't be exposed to the user, the return  value becomes important.</p>