title: Creating a Blocking Queue
body: <p>Sometimes this implementation and execution of <code>BlockingQueue</code> just works. Sometimes it segfaults. Any idea why?</p>
  
  <pre><code>#include &lt;thread&gt;
  using std::thread;
  #include &lt;mutex&gt;
  using std::mutex;
  #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;
  
  template &lt;typename T&gt;
  class BlockingQueue {
  private:
      mutex mutex_;
      queue&lt;T&gt; queue_;
  public:
      T pop() {
          this-&gt;mutex_.lock();
          T value = this-&gt;queue_.front();
          this-&gt;queue_.pop();
          this-&gt;mutex_.unlock();
          return value;
      }
  
      void push(T value) {
          this-&gt;mutex_.lock();
          this-&gt;queue_.push(value);
          this-&gt;mutex_.unlock();
      }
  
      bool empty() {
          this-&gt;mutex_.lock();
          bool check = this-&gt;queue_.empty();
          this-&gt;mutex_.unlock();
          return check;
      }
  };
  
  void fillWorkQueue(BlockingQueue&lt;string&gt;&amp; workQueue) {
      int size = 40000;
      for(int i = 0; i &lt; size; i++)
          workQueue.push(to_string(i));
  }
  
  void doWork(BlockingQueue&lt;string&gt;&amp; workQueue) {
      while(!workQueue.empty()) {
          workQueue.pop();
      }   
  }
  
  void multiThreaded() {
      BlockingQueue&lt;string&gt; workQueue;
      fillWorkQueue(workQueue);
      thread t1(doWork, ref(workQueue));
      thread t2(doWork, ref(workQueue));
      t1.join();
      t2.join();
      cout &lt;&lt; "done\n";
  }
  
  int main() {
      cout &lt;&lt; endl;
  
      // Multi Threaded
      cout &lt;&lt; "multiThreaded\n";
      multiThreaded();
      cout &lt;&lt; endl;
  }
  </code></pre>