title: Initializing pthread mutexes
body: <p>According to the <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_init.html" rel="noreferrer">documentation</a> a mutex can be initialized in two ways:</p>
  
  <p>Using the init function:</p>
  
  <pre><code>pthread_mutex_t theMutex;
  pthread_mutex_init(&amp;theMutex, NULL);
  </code></pre>
  
  <p>Using an initializer macro:</p>
  
  <pre><code>pthread_mutex_t result = PTHREAD_MUTEX_INITIALIZER;
  </code></pre>
  
  <p>About the latter the documentation says:</p>
  
  <blockquote>
    <p>In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.</p>
  </blockquote>
  
  <p>Does this mean that it may only be used for static variables and not for local variables?</p>
  
  <h3>C++ Specific</h3>
  
  <p>I wanted to use the following "factory function":</p>
  
  <pre><code>static pthread_mutex_t GetFastNativeMutex()
  {
      static pthread_mutex_t result = PTHREAD_MUTEX_INITIALIZER;
      return result;
  }
  </code></pre>
  
  <p>Because it would allow me to initialize mutexes in a C++ initializer list as follows:</p>
  
  <pre><code>MyClass() : myMutex(GetFastNativeMutex()) {}
  </code></pre>
  
  <p>Is this valid? (Btw in practice it works. Valgrind also doesn't complain.)</p>
  
  <h3>Update</h3>
  
  <p>If I understood the documentation correctly then this should be ok:</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  
  static pthread_mutex_t m0 = PTHREAD_MUTEX_INITIALIZER;
  static pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
  static pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
  </code></pre>
  
  <p>However, when looking at the preprocessor output (using <code>gcc -E main.cpp</code>) I see the following:</p>
  
  <pre><code>static pthread_mutex_t m0 = {0x32AAABA7, {0}};
  static pthread_mutex_t m1 = {0x32AAABA7, {0}};
  static pthread_mutex_t m2 = {0x32AAABA7, {0}};
  </code></pre>
  
  <p>It turns out that three times the same mutex was created. What am I doing wrong here?</p>