title: How to make a queue thread-safe
body: <p>Two threads working on this queue at the same time could make it fail. What will you do to make concurrent accesses work correctly? Should the queue make the threads wait if they try to remove an element from an empty queue or add one to a full one?</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  
  // circular array
  typedef struct _queue {
      int size;
      int used;
      int first;
      void **data;
  } _queue;
  
  #include "queue.h"
  
  queue q_create(int size) {
      queue q = malloc(sizeof(_queue));
  
      q-&gt;size  = size;
      q-&gt;used  = 0;
      q-&gt;first = 0;
      q-&gt;data = malloc(size*sizeof(void *));
  
      return q;
  }
  
  int q_elements(queue q) {
      return q-&gt;used;
  }
  
  int q_insert(queue q, void *elem) {
      if(q-&gt;size==q-&gt;used) return 0;
  
      q-&gt;data[(q-&gt;first+q-&gt;used) % q-&gt;size] = elem;    
      q-&gt;used++;
  
      return 1;
  }
  
  void *q_remove(queue q) {
      void *res;
      if(q-&gt;used==0) return NULL;
  
      res=q-&gt;data[q-&gt;first];
  
      q-&gt;first=(q-&gt;first+1) % q-&gt;size;
      q-&gt;used--;
  
      return res;
  }
  
  void q_destroy(queue q) {
      free(q-&gt;data);
      free(q);
  }
  </code></pre>
  
  <p>The objective of this queue is to manage the input and output of the compression tool I'm trying to develop.</p>