title: How to multithread queue processing
body: <p>C++ containers are <a href="http://en.cppreference.com/w/cpp/container" rel="nofollow">supposed to be thread-safe by default</a>. I must be using <code>queue</code> to multithread incorrectly because for this code:</p>
  
  <pre><code>#include &lt;thread&gt;
  using std::thread;
  #include &lt;iostream&gt;
  using std::cout;
  using std::endl;
  #include &lt;queue&gt;
  using std::queue;
  #include &lt;string&gt;
  using std::string;
  using std::to_string;
  #include &lt;functional&gt;
  using std::ref;
  
  
  void fillWorkQueue(queue&lt;string&gt;&amp; itemQueue) {
      int size = 40000;
      for(int i = 0; i &lt; size; i++)
          itemQueue.push(to_string(i));
  }
  
  void doWork(queue&lt;string&gt;&amp; itemQueue) {
      while(!itemQueue.empty()) {
          itemQueue.pop();
      }   
  }
  
  void singleThreaded() {
      queue&lt;string&gt; itemQueue;
      fillWorkQueue(itemQueue);
      doWork(itemQueue);
      cout &lt;&lt; "done\n";
  }
  
  void multiThreaded() {
      queue&lt;string&gt; itemQueue;
      fillWorkQueue(itemQueue);
      thread t1(doWork, ref(itemQueue));
      thread t2(doWork, ref(itemQueue));
      t1.join();
      t2.join();
      cout &lt;&lt; "done\n";
  }
  
  int main() {
      cout &lt;&lt; endl;
  
      // Single Threaded
      cout &lt;&lt; "singleThreaded\n";
      singleThreaded();
      cout &lt;&lt; endl;
  
      // Multi Threaded
      cout &lt;&lt; "multiThreaded\n";
      multiThreaded();
      cout &lt;&lt; endl;
  }
  </code></pre>
  
  <p>I'm getting:</p>
  
  <pre><code>singleThreaded
  done
  
  multiThreaded
  main(32429,0x10e530000) malloc: *** error for object 0x7fe4e3883e00: pointer being freed was not allocated
  *** set a breakpoint in malloc_error_break to debug
  make: *** [run] Abort trap: 6
  </code></pre>
  
  <p>What am I doing wrong here?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Apparently I misread the link above. Is there a thread-safe queue implementation available that does what I am trying to do? I know this is a common thread organization strategy.</p>