title: Double free or corruption (!prev) error when working with threads and mutex
body: <p>I've got simple c++ code that firstly creates 4 threads and then sends 1000 times number 1 to the c++ queue followed by four 0. Each of these threads tries to read from that queue and when any thread reads 0, it terminates and prints its local sum. If it reads 1 then it simply adds 1 to the sum. The reading is protected with mutex. Code works as intended in 4 out of 5 times, but sometimes I get <code>double free or corruption (!prev) error... ...Abort core dumped</code>. I've also debugged the code with gdb but only got <code>received signal SIGABRT, Aborted ... ...at raise.c: No such file or directory".</code> I'm not explicitly allocating or deallocating any memory. What could be causing the problem?</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;queue&gt;
  
  std::queue&lt;int&gt; my_queue;
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  
  void *process(void *arg){
      int sum = 0;
      while(1){
          if(!my_queue.empty()){
              pthread_mutex_lock(&amp;mutex);
              if (my_queue.front() == 1){
                  sum += 1;
                  my_queue.pop();
                  pthread_mutex_unlock(&amp;mutex);
              }
              else{
                  my_queue.pop();
                  printf("Sum: %d\n", sum);
                  pthread_mutex_unlock(&amp;mutex);
                  break;
              }
          }
      }
      return arg;
  }
  
  int main(void){
      pthread_t id[4];
      for(int i = 0; i &lt; 4; i++){
          if (pthread_create(&amp;id[i], NULL, process, NULL) != 0){
              fprintf(stderr, "%s\n", "Error creating thread!");
              exit(EXIT_FAILURE);
          }
      }
      for (int i = 0; i &lt; 1000; i++){
          my_queue.push(1);
      }
      for (int i = 0; i &lt; 4; i++){
          my_queue.push(0);
      }
      for (int i = 0; i &lt; 4; i++){
          pthread_join(id[i], NULL);
      }
      return EXIT_SUCCESS;
  }
  </code></pre>