title: Stopping C++ 11 std::threads waiting on a std::condition_variable
body: <p>I am trying to understand the basic multithreading mechanisms in the new C++ 11 standard. The most basic example I can think of is the following:</p>
  
  <ul>
  <li>A producer and a consumer are implemented in separate threads</li>
  <li>The producer places a certain amount of items inside a queue</li>
  <li>The consumer takes items from the queue if there are any present</li>
  </ul>
  
  <p>This example is also used in many school books about multithreading and everything about the communication process works fine. However, I have a problem when it comes to stopping the consumer thread. </p>
  
  <p>I want the consumer to run until it gets an explicit stop signal (in most cases this means that I wait for the producer to finish so I can stop the consumer before the program is ended). Unfortunately C++ 11 threads lack an interrupt mechanism (which I know from multithreading in Java for example). Thus, I have to use flags like <code>isRunning</code> to signal that I want a thread to stop.</p>
  
  <p>The main problem now is: After I have stopped the producer thread, the queue is empty and the consumer is waiting on a <code>condition_variable</code> to get a signal when the queue is filled again. So I need to wake the thread up by calling <code>notify_all()</code> on the variable before exiting.</p>
  
  <p>I have found a working solution, but it seems somehow messy.
  The example code is listed below (I am sorry but somehow I couldn't reduce the code size any furhter for a "minimal" minimal example):</p>
  
  <p>The Queue class:</p>
  
  <pre><code>class Queue{
  public:
      Queue() : m_isProgramStopped{ false } { }
  
      void push(int i){
          std::unique_lock&lt;std::mutex&gt; lock(m_mtx);
          m_q.push(i);
          m_cond.notify_one();
      }
  
      int pop(){
          std::unique_lock&lt;std::mutex&gt; lock(m_mtx);
          m_cond.wait(lock, [&amp;](){ return !m_q.empty() || m_isProgramStopped; });
  
          if (m_isProgramStopped){
              throw std::exception("Program stopped!");
          }
  
          int x = m_q.front();
          m_q.pop();
  
          std::cout &lt;&lt; "Thread " &lt;&lt; std::this_thread::get_id() &lt;&lt; " popped " &lt;&lt; x &lt;&lt; "." &lt;&lt; std::endl;
          return x;
      }
  
      void stop(){
          m_isProgramStopped = true;
          m_cond.notify_all();
      }
  
  private:
      std::queue&lt;int&gt; m_q;
      std::mutex m_mtx;
      std::condition_variable m_cond;
      bool m_isProgramStopped;
  };
  </code></pre>
  
  <p>The Producer:</p>
  
  <pre><code>class Producer{
  public:
      Producer(Queue &amp; q) : m_q{ q }, m_counter{ 1 } { }
  
      void produce(){
          for (int i = 0; i &lt; 5; i++){
              m_q.push(m_counter++);
              std::this_thread::sleep_for(std::chrono::milliseconds{ 500 });
          }
      }
  
      void execute(){
          m_t = std::thread(&amp;Producer::produce, this);
      }
  
      void join(){
          m_t.join();
      }
  
  private:
      Queue &amp; m_q;
      std::thread m_t;
  
      unsigned int m_counter;
  };
  </code></pre>
  
  <p>The Consumer:</p>
  
  <pre><code>class Consumer{
  public:
      Consumer(Queue &amp; q) : m_q{ q }, m_takeCounter{ 0 }, m_isRunning{ true }
      { }
  
      ~Consumer(){
          std::cout &lt;&lt; "KILL CONSUMER! - TOOK: " &lt;&lt; m_takeCounter &lt;&lt; "." &lt;&lt; std::endl;
      }
  
      void consume(){
          while (m_isRunning){
              try{
                  m_q.pop();
                  m_takeCounter++;
              }
              catch (std::exception e){
                  std::cout &lt;&lt; "Program was stopped while waiting." &lt;&lt; std::endl;
              }
          }
      }
  
      void execute(){
          m_t = std::thread(&amp;Consumer::consume, this);
      }
  
      void join(){
          m_t.join();
      }
  
      void stop(){
          m_isRunning = false;
      }
  
  private:
      Queue &amp; m_q;
      std::thread m_t;
  
      unsigned int m_takeCounter;
      bool m_isRunning;
  };
  </code></pre>
  
  <p>And finally the <code>main()</code>:</p>
  
  <pre><code>int main(void){
      Queue q;
  
      Consumer cons{ q };
      Producer prod{ q };
  
      cons.execute();
      prod.execute();
  
      prod.join();
  
      cons.stop();
      q.stop();
  
      cons.join();
  
      std::cout &lt;&lt; "END" &lt;&lt; std::endl;
  
      return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p>Is this the <em>right</em> way to end a thread that is waiting an a condition variable or are there better methods? Currently, the queue needs to know if the program has stopped (which in my opinion destroys the loose coupling of the components) and I need to call <code>stop()</code> on the queue explicitly which doesn't seem right.</p>
  
  <p>Additionaly, the condition variable which should just be used as a singal if the queue is empty now stands for another condition - if the program has ended. If I am not mistaken, every time a thread waits on a condition variable for some event to happen, it would also have to check if the thread has to be stopped before continuing its execution (which also seems wrong).</p>
  
  <p>Do I have these problems because my entire design is faulty or am I missing some mechanisms that can be used to exit threads in a clean way?</p>