title: What happens when calling the destructor of a thread object that has a condition variable waiting?
body: <p>I am using a <code>SynchronisedQueue</code> to communicate between threads. I found that destroying the thread object when the attaching thread is waiting on a condition variable would cause the program crash. This can be corrected by calling <code>detach()</code> before the thread destruction. But I am wondering what happens exactly when a thread waiting a conditional variable got terminated. Is there another way to use condition variable to avoid this?</p>
  
  <pre><code>#include &lt;queue&gt;
  #include &lt;thread&gt;
  #include &lt;mutex&gt;
  #include &lt;condition_variable&gt;
  
  template &lt;typename Type&gt; class SynchronisedQueue {
   public:
    void Enqueue(Type const &amp; data) {
      std::unique_lock&lt;std::mutex&gt; lock(mutex_);
      queue_.push(data);
      condition_.notify_one();
    }
    Type Dequeue() {
      std::unique_lock&lt;std::mutex&gt; lock(mutex_);
      while (queue_.empty())
        condition_.wait(lock);
      Type result = queue_.front();
      queue_.pop();
      return result; 
    }
   private:
    std::queue&lt;Type&gt; queue_;
    std::mutex mutex_;
    std::condition_variable condition_; 
  };
  
  class Worker {
  public:
    Worker(SynchronisedQueue&lt;int&gt; * queue) : queue_(queue) {}
    void operator()() {
      queue_-&gt;Dequeue();    // &lt;-- The thread waits here.
    }
  private:
    SynchronisedQueue&lt;int&gt; * queue_;
  };
  
  int main() {
    auto queue = new SynchronisedQueue&lt;int&gt;();
    Worker worker(queue);
    std::thread worker_thread(worker);
    worker_thread.~thread();  // &lt;-- Crashes the program.
    return 0;
  }
  </code></pre>