title: `pthread_mutex_trylock` blocks when called by two threads at the same time
body: <p>I'm using <code>pthread_mutex_trylock</code> to lock the mutex on a struct so that it can only be accessed/modified by a single thread at a given time. If the mutex is already locked I just return from the routine rather than queuing/blocking.</p>
  
  <p>This is a basic outline of my code:</p>
  
  <pre><code>typedef struct {
      pthread_mutex_t m;
  } myStruct;
  
  void setupStruct(myStruct* struc) {
      pthread_mutex_init(&amp;struc-&gt;m, NULL);
  }
  
  void structOp(myStruct* struc) {
  
      printf("structOp(): Trying to lock\n");
  
      if(pthread_mutex_trylock(&amp;struc-&gt;m) != 0) {
          printf("structOp(): Lock failed\n");
          return;
      } else {
          printf("structOp(): Locked\n");
          // do some stuff to struct
          pthread_mutex_unlock(&amp;struc-&gt;m);
      }
  }
  </code></pre>
  
  <p>The struct is initialised once like this:</p>
  
  <pre><code>myStruct* struc = malloc(sizeof(struc));
  setupStruct(struc);
  </code></pre>
  
  <p>However, sometimes when two threads call a routine at the same time both calls to <code>trylock</code> seem to block. I'm assuming this because it prints "Trying to lock" for both threads at the same time, but does not print whether or not the mutex was locked. I was originally having this problem with <code>pthread_mutex_lock</code> so tried the non-blocking version for this reason, but it still seems to block.</p>
  
  <p>This doesn't always happen but when it does it's always the <strong>first two</strong> calls to the routine. If the first two calls run fine, then subsequent calls also work fine.</p>
  
  <p>Is there any reason this would block? Am I just incorrectly perceiving this blocking due to some other problem? I can post other parts of my code if the problem may lie elsewhere.</p>