title: How to implement thread safe queues
body: <p>I have used multithreading library before in Python, but this is the first time I am trying threading in C. I want to create pool of workers. In turn, these workers supposed to push to or pop from queue.Following code is not quite there yet, but is what I have done so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  #define NUMTHREADS 20 /* number of threads to create */
  
  typedef struct node node;
  typedef struct queue queue;
  
  struct node {
      char *name;
      node *next;
  };
  
  struct queue {
      node *head;
      node *tail;
  };
  
  /* pop: remove and return first name from a queue */
  char *pop(queue *q)
  {
      if (q-&gt;head == NULL)
          return NULL;
      char *name = q-&gt;head-&gt;name;
      node *tmp = q-&gt;head;
      q-&gt;head = q-&gt;head-&gt;next;
      free(tmp);
      return name;
  }
  
  /* push: add name to the end of the queue */
  int push(queue *q, char *name)
  {
      node *new = malloc(sizeof(node));
      if (new == NULL)
          return -1;
      new-&gt;name = name;
      new-&gt;next = NULL;
      if (q-&gt;tail != NULL)
          q-&gt;tail-&gt;next = new;
  
      q-&gt;tail = new;
      if (q-&gt;head == NULL) /* first value */
          q-&gt;head = new;
      return 0;
  }
  
  /* printname: get a name from the queue, and print it. */
  void *printname(void *sharedQ)
  {
      queue *q = (queue *) sharedQ;
      char *name = pop(q);
      if (name == NULL)
          pthread_exit(NULL);
      printf("%s\n",name);
      pthread_exit(NULL);
  }
  
  int main()
  {
      size_t i;
      int rc;
      pthread_t threads[NUMTHREADS];
      char *names[] = {
          "yasar",
          "arabaci",
          "osman",
          "ahmet",
          "mehmet",
          "zeliha"
      };
  
      queue *q = malloc(sizeof(queue));
      q-&gt;head = NULL;
      q-&gt;tail = NULL;
  
      /* number of elements in the array */
      size_t numelems = sizeof(names) / sizeof(char *);
  
      for (i = 0; i &lt; numelems; i++) /* push each name */
          push(q, names[i]);
  
      for (i = 0; i &lt; NUMTHREADS; i++) { /* fire up threads */
          rc = pthread_create(&amp;threads[i], NULL, printname,
                  (void *)q);
          if (rc) {
              printf("Error, return code from pthread is %d\n", rc);
              exit(-1);
          }
      }
  
      pthread_exit(NULL);
  }
  </code></pre>
  
  <p>I tried above code, and it always printed each name exactly once. It didn't skip any names, or printed same name twice. On the other hand, I am not sure how thread safe this queue implementation is. So my question is, Is this a threadsafe queue? If not, why not? And how to make it thread safe?</p>